Deep understanding of JavaScript series (20): Do you really understand JavaScript? Explanation

Source: Internet
Author: User
Introduction

Uncle Shouji (19) posted yesterday: Do you really understand JavaScript? There are a lot of answers to the five questions in it. I found that there are still many strong people, and many people have all answered correctly.

Today, we will analyze these five questions in detail and hope to help you.

Note:

 
The question is from the post "so, you think you know JavaScript?" by baranovskiy, a well-known front-end architect.
The answer is also from the well-known JavaScript cool-man Nicholas C. zakas's post answering baranovskiy's JavaScript quiz-JavaScript advancedProgramOriginal Author of Design
(But the explanation for Question 2 seems a bit problematic)

OK. Let's take a look at the first question first.

Question 1
 
If(! (""InWindow )){
VaRA = 1;
}
Alert ();

CodeIt looks like: if the window does not contain attribute a, it declares a variable A and assigns a value to 1.

You may think that the result of alert is 1, and then the actual result is "undefined ". To understand why, we need to know three concepts in JavaScript.

First, all global variables are the properties of window. The statement var A = 1 is equivalent to window. A = 1. You can check whether global variables are declared in the following way:

"Variable name"InWindow

Second, all variable declarations are at the top of the scope. Let's take a look at similar examples:

 
Alert (""InWindow );
VaRA;

At this point, although the Declaration is after alert, the alert pop-up is still true, because the JavaScript engine will first scan all the variable declarations and then move these variable declarations to the top, the final code effect is as follows:

 
VaRA;
Alert (""InWindow );

This makes it easy to explain why the alert result is true.

Third, you need to understand the meaning of this question: the variable declaration is advanced, but the variable assignment is not, because this line of code includes the variable declaration and variable assignment.

You can split the statement into the following code:

 
VaRA;//Statement
A = 1;//Initialize assignment

When the variable declaration and value assignment are used together, the JavaScript engine automatically divides the variable declaration into two parts to advance the variable declaration, the procedure of not assigning values in advance is because it may affect the code execution to produce unexpected results.

So after understanding these concepts, you can look back at the code of the question, which is equivalent:

 
VaRA;
If(! (""InWindow )){
A = 1;
}
Alert ();

In this way, the meaning of the question is very clear: first declare a, and then judge whether a exists. If it does not exist, the value is assigned to 1. Obviously, a will always exist in the window, this assignment statement will never be executed, so the result is undefined.

Uncle note:AdvanceThis word is a bit confusing. It is actually the relationship between the execution context, because the execution context is divided into two stages: the execution context and the Execution Code. When the execution context is entered, the created variable object VO already has all the parameters of the function, all the function declarations, and all the variable declarations.

 
VO (global) = {
A: Undefined
}

At this time, a already exists;

The IF statement is followed only when the code is executed. For more information, see "Understanding JavaScript series (12): Variable object).

Uncle Note: I believe many people think that A is not accessible in it, and the result is undefined. Actually, it already exists, but the initial value is undefined rather than inaccessible.

Question 2
VaRA = 1,
B =FunctionA (x ){
X & A (-- X );
};
Alert ();

This question seems more complex than it is. The result of alert is 1. Here there are three important concepts that need to be known.

First, in question 1, we know that the variable declaration is completed when it enters the execution context. The second concept is that the function declaration is also in advance, all function declarations have been declared and changed before the code is executed.

The volume declaration is the same. To clarify, the function declaration is the following code:

 
FunctionFunctionname (arg1, arg2 ){
//Function body
}

The following is not a function, but a function expression, which is equivalent to a variable value assignment:

 
VaRFunctionname =Function(Arg1, arg2 ){
//Function body
};

To clarify, if the function expression is not in advance, it is equivalent to the variable assignment at ordinary times.

Third, the function declaration will overwrite the variable declaration, but will not overwrite the variable assignment. To explain this, let's look at an example:

 
FunctionValue (){
Return1;
}
VaRValue;
Alert (TypeofValue );//"Function"

The variable declaration is defined below as soon as possible, but the variable value is still a function. That is to say, in this case, the priority of the function declaration is higher than that of the variable declaration, but if the variable value is assigned a value, the results are completely different:

 
FunctionValue (){
Return1;
}
VaRValue = 1;
Alert (TypeofValue );//"Number"

After the value is assigned, the variable value initialization overwrites the function declaration.

Return to the question. This function is actually a famous function expression. The function expression can overwrite the variable declaration like the function declaration, but you can note that variable B contains the function expression, the name of the function expression is a. Different browsers have different processing methods for the term a. in IE, A considers function declaration as a function, so it is overwritten by variable initialization, that is to say, if a (-- X) is called, an error will occur, while other browsers allow calling a (-- X) within the function, because at this time a is still a number outside the function. Basically, an error occurs when B (2) is called in IE, but undefined is returned in other browsers.

After understanding the above content, the question should be replaced with a more accurate and easier-to-understand code like this:

 
VaRA = 1,
B =Function(X ){
X & B (-- X );
};
Alert ();

In this way, we can clearly understand why alert is always 1. For details, see the content in "Understanding JavaScript series (2): Revealing the name of a function expression.

Uncle Note: When the ecmascript specification is installed, the author's interpretation of the function declaration override variable declaration is not accurate. The correct understanding should be as follows:

Enter execution Context: The name is the same. One is the function declaration and the other is the variable declaration. So, according to a deep understanding of JavaScript series (12): Variable object, the filling order of VO is: function parameters-> function declaration-> variable declaration.
In the preceding example, variable A is behind function A. What if variable A encounters function? As described in the variable object, when the variable Declaration has the same name in Vo, the existing attributes will not be affected. Function expressions do not affect VO content. Therefore, B triggers the content only during execution.

Question 3
 
FunctionA (x ){
ReturnX * 2;
}
VaRA;
Alert ();

This topic is the comment added by Uncle in question 2, that is, the relationship and impact of function declaration and variable declaration. VO will not redefine the function declaration with the same name, at this time, the global VO should be as follows:

 
VO (global) = {
A: reference the function declaration ""
}

When a is executed, the content of function a is displayed accordingly.

Question 4
 
FunctionB (X, Y, ){
Arguments [2] = 10;
Alert ();
}
B (1, 2, 3 );

On this topic, NC has moved out of the 262-3 specification and explained it. In fact, from the "deep understanding of JavaScript series (12): Variable object) the variable object section in the function context clearly shows that the active object is created when the context of the function is entered. It is initialized through the arguments attribute of the function. The value of the arguments attribute is an arguments object:

 
Ao = {
Arguments: <Argo>
};

An arguments object is an attribute of an activity object. It includes the following attributes:

    1. Callee-reference to the current function
    2. Length-Number of actually passed parameters
    3. The properties-indexes (an integer of the string type) attribute value is the parameter value of the function (arranged from left to right by the parameter list ). The number of elements in properties-indexes is equal to that of arguments. length. properties-indexes.Share.

In fact, this sharing is not really a shared memory address, but two different memory addresses. the JavaScript engine is used to ensure that the two values are the same at any time. Of course, this also has a premise, that is, the index value is smaller than the number of parameters you pass in. That is to say, if you pass in only two parameters and continue to use the arguments [2] value assignment, it will be inconsistent. For example:

 
FunctionB (X, Y, ){
Arguments [2] = 10;
Alert ();
}
B (1, 2 );

At this time, because the third parameter A is not passed, the result of alert (a) is still undefined, not 10 after the value is assigned, but the result of the following code is still 10, because it has nothing to do with.

 
FunctionB (X, Y, ){
Arguments [2] = 10;
Alert (arguments [2]);
}
B (1, 2 );

Question 5
FunctionA (){
Alert (This);
}
A. Call (Null);

This question can be said to be the simplest and the most strange, because if you do not learn its definition, you will not know the result. For this question, we will first understand two concepts.

First, how is the value of this defined? When a method is called on an object, this points to this object. For example:

 
VaRObject = {
Method:Function(){
Alert (This=== Object );//True
}
}
Object. Method ();

The above code points this to the object that calls method (), but in the global scope, this is equivalent to window (in a browser, non-Browsers are equivalent to global). When a function is defined as an object attribute (that is, a function defined separately ), the internal value of this in the function is equal to that of window, for example:

FunctionMethod (){
Alert (This=== Window );//True
}
Method ();

After learning about the above concepts, let's take a look at what call () is doing. The call method, as a function execution, indicates that this method can be called by another object as the caller, the first parameter of the call method is the object caller, and other parameters are the parameters to be passed to the call method (if declared). For example:

 
FunctionMethod (){
Alert (This=== Window );
}
Method ();//True
Method. Call (document );//False

There is nothing to say about the first is true, and the second incoming call object is document, which is not equal to window, so false is displayed.

In addition, according to ecmascript262: If the caller of the object passed in by the first parameter is null or undefined, the call method regards the Global Object (that is, window) as the value of this. Therefore, no matter when you pass in null, this is a global Object window, so this question can be understood as the following code:

 
FunctionA (){
Alert (This);
}
A. Call (window );

The pop-up result is [Object window], which is easy to understand.

Summary

Although these five questions seem to be a bit biased, they actually look at the basic concepts. Only by familiarizing themselves with these basic concepts can we write high-quality code.

The basic core content and understanding of JavaScript is basically the end of this series. In addition to completing the remaining two of the five principles, I will add two more articles about DomArticleThen I started to sort out articles about the Javascript mode and design mode (about 10 articles). Then I will spend several chapters on a practical series.

More questions

If you are interested, you can continue to study the following questions. Through these questions in detail, you can also deepen your understanding of the basic core features of JavaScript.

Uncle Note: These questions are also from those five questions. Of course, if you can answer four or more questions and want to raise your salary, please contact me.

    1. Find the largest element in the number array (use the match. Max function)
    2. Convert a number array to a Function Array (corresponding numbers are displayed for each function)
    3. Sort the object array (the sorting condition is the number of attributes of each element object)
    4. Print the number of Fibonacci using JavaScript (do not use global variables)
    5. Implement the following syntax functions: var A = (5). Plus (3). Minus (6); // 2
    6. Implement the following syntax functions: var A = add (2) (3) (4); // 9

Transferred from: Uncle Tom

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.