Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common JavaScript knowledge points?

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the common JavaScript knowledge points". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the common JavaScript knowledge points"?

1. Statement

Look at the following code and answer the contents of the output (and why).

/ / situation 1 console.log (person); var person = 'John'; / / situation 2 console.log (person); let person =' Phill'; / / situation 3 console.log (person); const person = 'Frank'; / / situation 4 const person =' Vanessa'; console.log (person); person = 'Mike'; console.log (person); / / situation 5 var person =' John'; let person = 'Mike'; console.log (person); / / situation 6 var person =' John' If (person) {let person = 'Mike'; console.log (person);} console.log (person)

Description

Situation 1: the expected result is to see the text John in the console, but surprisingly, we see that the undefined is recorded. Want to know why?

Well, this is the classic JavaScript at work. This behavior is called ascension. In the background, the language divides variable declaration and value assignment into two parts. No matter where the variable is originally declared by the developer, the variable moves to the top and its value is set to undefined when declared. It looks like this:

Var person; console.log (person); person = 'John'

Situation 2: in this case, the result will be a reference error.

Uncaught ReferenceError: Cannot access' person' before initialization

The error text speaks for itself. Because we used the keyword let, our variable was promoted but not initialized, and the error was thrown to inform us that we were trying to access the uninitialized variable. The keyword let has been introduced into ES6 to enable us to use variables in the block scope, which helps us prevent unexpected behavior.

Here, we get the same error as in Situation 2.

The difference is that we use the keyword const to prevent reallocation of variables after initialization. This keyword is also introduced in ES6.

Situation 4: in this case, we can see how the keyword const works and how it avoids inadvertently reassigning variables. In our example, we will first see Vanessa in the console, followed by a type error.

Uncaught TypeError: Assignment to constant variable

The use of const variables increases exponentially with our code base.

Situation 5: if a variable has been defined with the keyword var in a scope, declaring the variable again with the keyword let in the same scope will raise an error.

Therefore, in our example, nothing will be output and you will see a syntax error prompt.

Uncaught SyntaxError: Identifier 'person' has already been declared

Situation 6: we have a function-scoped variable and a block-scoped variable. In this case, it doesn't matter whether they have the same name or identifier.

In the console, we should see that Mike and John are output in turn. Why?

Because the keyword let provides us with variables within the scope of the block, this means that they only exist in the scope created by ourselves, in this case, in the if...else statement. Internal variables take precedence over external variables, which is why we can use the same identifier.

two。 Inherit

Consider the following classes and try to answer what is output and why.

Class Person {constructor () {this.sayHello = () = > {return 'Hello';}} sayBye () {return' Bye';}} class Student extends Person {sayHello () {return 'Hello from Student';}} const student = new Student (); console.log (student.sayHello ())

Description

If your answer is Hello, that's right!

Why: every time we create a new Student instance, we set the sayHello property to be a function and return the string Hello. This occurs in the constructor of the parent class (Person).

In JavaScript, the class is the syntactic sugar, and in our example, the sayHello method in the Student class is defined on the prototype chain. Considering that every time we create an instance of the Student class, we set the sayHello property to that instance to make it the function that returns the string Hello, so we will never use the function defined on the prototype chain and never see the message Hello from Student.

3. Object variability

Consider the output of each part of the following scenario:

/ / situation 1 const user = {name: 'John', surname:' Doe'} user = {name: 'Mike'} console.log (user); / / situation 2 const user = {name:' John', surname: 'Doe'} user.name =' Mike'; console.log (user.name); / / situation 3 const user = {name: 'John', surname:' Doe'} const anotherUser = user; anotherUser.name = 'Mike' Console.log (user.name); / / situation 4 const user = {name: 'John', surname:' Doe', address: {street:'My Street'}} Object.freeze (user); user.name = 'Mike'; user.address.street =' My Different Street'; console.log (user.name); console.log (user.address.street)

Description

Situation 1: as we learned in the previous section, we try to reassign const variables that are not allowed, so we will get a type error.

The results in the console display the following text:

Uncaught TypeError: Assignment to constant variable

Situation 2: in this case, even if we use the keyword const to declare variables, we will behave differently. The difference is that we are modifying object properties instead of their references, which is allowed in the const object variable.

The result in the console should be the word Mike.

Situation 3: by assigning user to the anotherUser variable, you can share references or storage locations between them (if you prefer). In other words, they both point to the same object in memory, so changing the properties of one object will reflect the changes of the other.

The result in the console should be Mike.

Situation 4: here, we use the Object.freeze method to provide functionality that was lacking in the previous scenario (Situation 3). With this method, we can "freeze" the object so that its property values are not allowed to be modified. But there is one problem! It only freezes shallowly, which means it does not protect updates to deep properties. This is why we can make changes to the street property while leaving the name property unchanged.

The output in the console is John and My Different Street in turn.

4. Arrowhead function

After running the following code snippet, what will be output and why:

Const student = {school:'My School', fullName: 'John Doe', printName: () = > {console.log (this.fullName);}, printSchool: function () {console.log (this.school);}}; student.printName (); student.printSchool ()

Description

The output in the console will be undefined and My School in turn.

You may be familiar with the following syntax:

Var me = this; / / or var self = this; / /... /... / / somewhere deep... / / me.doSomething ()

You can think of a me or self variable as a parent scope, which can be used for each nested function created in it.

This is done automatically when using the arrow function, and we no longer need to store this references to access deeper places in the code. The arrow function does not bind itself, but inherits an arrow function from the parent scope, which is why the undefined is output after calling the printName function.

5. Deconstruction

Please review the destruction information below and answer what you are going to output. Is the given syntax allowed, otherwise an error will be raised?

Const rawUser = {name: 'John', surname:' Doe', email: 'john@doe.com', displayName:' SuperCoolJohn', joined: '2016-05-05, image:' path-to-the-image', followers: 45} let user = {}, userDetails = {}; ({name: user.name, surname: user.surname,... userDetails} = rawUser); console.log (user); console.log (userDetails)

Description

Although it's a little out of the box, the above syntax is allowed and does not cause an error! Isn't it neat?

The syntax above is so powerful that we can easily divide any object into two more specific objects. The output of the above example on the console is:

/ / {name: "John", surname: "Doe"} / / {email: "john@doe.com", displayName: "SuperCoolJohn", joined: "2016-05-05", image: "path-to-the-image", followers: 45}

6. Async / wait

What will be output after calling the following function?

(async () = > {let result = 'Some Data'; let promise = new Promise ((resolve, reject) = > {setTimeout () = > resolve (' Some data retrieved from the server'), 2000);}); result = await promise; console.log (result);}) ()

Description

If you think it will output Some data retrieved from the server in two seconds, then you are right!

The code will be paused until the promise is resolved. After two seconds, it will continue to execute and output the given text. This means that the JavaScript engine actually waits for the asynchronous operation to complete. It can be said that async/await is a grammatical sugar used to obtain promise results. Others think it is a more readable way than promise.then.

7. Return statement

Const multiplyByTwo = (x) = > {return {result: X * 2};} console.log (multiplyByTwo (2))

Description

If your answer is {result: 4}, you are wrong. The output is undefined. But don't be too hard on yourself, considering that I also write C # code, which used to bother me, which is not a problem in C #.

Due to automatic semicolon insertion, the above code returns undefined. Line Terminator is not allowed between return keyword and expression

The solution is to fix this function in one of the following ways:

Const multiplyByTwo = (x) = > {return {result: X * 2};} or const multiplyByTwo = (x) = > {return ({result: X * 2}) } Thank you for your reading, the above is the content of "what are the common JavaScript knowledge points". After the study of this article, I believe you have a deeper understanding of the common JavaScript knowledge points, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report