JS interview pit: Variable boost

Source: Internet
Author: User

Parsing and execution procedures in the global

Preprocessing: Create a lexical environment (lexicalenvironment, which is abbreviated as LE), scan JS for declaring functions declaratively, variables defined with Var, and add them to the lexical context of the preprocessing phase.

First, how to understand the preprocessing in the global environment

For example, the following code:

var a = 1;//variables defined with Var to assign Var b;//variables defined with var, unassigned C = 3;//Undefined, direct assignment function D () {//functions declared in declarative form    console.log (' Hello ');} var e = function () {//Functions expression    console.log (' World ');}

The lexical scopes it creates during preprocessing can be represented as:

le{        //At this time Le is equivalent    to window a:undefined    b:undefined    no c    D: a reference to the function    without e}

Emphasis: 1. The preprocessing function must be a function (not a function expression) declared by JS in a declarative way, see example:

D (); E (); function d () {//Console.log of functions declared declaratively    (' Hello ');} var e = function () {//Functions expression    console.log (' World ');}

The output results are: Hello; error e is not a function
2, is the variable defined by VAR, see example:

Console.log (a);//undefinedconsole.log (b);//undefinedconsole.log (c);//Error: C is not definedvar a = 1;var b;c = 3;
Ii. handling of naming conflicts

Look at the following code: What do you think the output is?

Console.log (f); var F = 1;function F () {    console.log (' Foodoir ');}
Console.log (f); function f () {    console.log (' Foodoir ');} var f = 1;
Console.log (f); var F = 1;var F = 2;
Console.log (f); function f () {    console.log (' Foodoir ');} function f () {    console.log (' Hello World ');}

You may as well start with me, think the output is foodoir, so you are wrong, you should continue to look at the pre-treatment of the problem. The result of the first code output should be: function f () {Console.log (' Foodoir ');}.

When you see the second piece of code, you may not want to answer the result is 1, and you also tell the reason that JavaScript functions do not have the traditional meaning of overloading. Yes, the function in JavaScript is not overloaded, but the second piece of code still runs: function f () {Console.log (' Foodoir ');}. (Explanation after reason)

If you still think the result of the third piece of code is 2 or 1, then I suggest you go back to the previous example of preprocessing. The result of the third paragraph is: undefined.

The result of the fourth code is function f () {Console.log (' Hello World ');}

Cause: The processing function declaration is overwritten when there is a conflict, and is ignored when the handling variable declaration has a conflict. In the case of both function declarations and variable declarations, you can understand as much as I do in CSS, the weight of function declarations is always higher, so the end result is often a reference to a function declaration.

Third, the execution of the global function

Take a look at the following example:

1 Console.log (a); 2 Console.log (b); 3 Console.log (c); 4 Console.log (d); 5 var a = 1; 6 B = 2; 7 Console.log (b); 8 function C () {9     console.log (' C ');}11-var d = function () {     console.log (' d ');}15 Console.log (d);

1, we first analyze the situation of global preprocessing, the results are as follows:

le{    a:undefined    no b    C: a reference to a function    d:undefined}

At this point, we can get the first four lines of code to get the results, respectively:
Undefined
Error
Function C () {Console.log (' C ');
Undefined

2. When the preprocessing is finished, the code begins to parse (comment out the code of the second line error)

After the 6th line of code executes, the value of a in Le is changed to 1;

le{    a:1    no b    C: a reference to a function    d:undefined}

The 7th line of code executes, and Le has a value of B (and the value of B is 2, at which point the value of B directly becomes the global variable);

le{    a:1    b:2    C: A reference to a function    d:undefined}

The 10th line of code finishes executing,

le{    a:1    b:2    C: Point to function    d:undefined}

The 14th line of code finishes executing, at which point

le{    a:1    b:2    C: Point to function    D: point to Function}

As an example of the change of B into a global variable, we enter WINDOW.B in the console, and we can get a result of B of 2. Results

Add: Using the lexical scope, we can well explain an example of a function with multiple parameters passing only one parameter.

function f (A, B) {    }f (1);

Its lexical scope can be interpreted as:

le{    a:1    b:undefined}
Parsing and execution procedures in a function

The difference between parsing and executing in a function is not very large, but there is a arguments in the function we need to take a look at the following example:

function f (A, b) {    alert (a);    alert (b);        var B = +;    function A () {}}f (UP);

We first analyze the preprocessing of the function, which is similar to the global preprocessing, and its lexical structure is as follows:

le{    B:2    A: a reference to a function    arguments:2}//arguments, the number of arguments actually called when the function is called

The previous sentence: When a handler declaration has a conflict, it is overwritten, there is a conflict when handling the variable declaration, and it is ignored.
The results were: function A () {} and 2

When the passed parameter value has one:

function f (A, b) {    alert (a);    alert (b);        var B = +;    function A () {}}f (1);

The lexical structure at this time is as follows:

le{    b:undefined    A: a reference to a function    arguments:1}

The results were: function A () {} and undefined
There is also a need to note that if there is no variable declared with VAR, it will become the member of the most external le, that is, the global variable

function A () {    function B () {        g = n;    }    b ();} A (); Console.log (g);//12

Console results:

With the previous foundation, we can have a deep understanding of the scope and scope chain of JS.

About the JS scope and the scope chain
Console.log (a);//undefinedconsole.log (b);//undefinedconsole.log (c);//c is not definedconsole.log (d);//d are not Definedvar A = 1;if (false) {    var b = 2;} else{    c = 3;} function f () {    var d = 4;}

With the previous basics we can easily get the top three results, but for the fourth one there is a lot of doubt, and it's time to take a look at the knowledge of JavaScript scopes.
In programming languages, scopes can generally be divided into four categories: block-level scope, function scope, dynamic scope, lexical scope (also known as static scope)

Block-level scopes

In other C-class languages, the parts enclosed in curly braces are called scopes, but there is no block-level scope for JavaScript, so consider the following example:

for (Var i=0;i<3;i++) {    //}console.log (i);

It has a result of 3, because after executing the for loop, the value of I at this point is 3 and remains valid after

function scope

There is no purely functional scope

Dynamic scopes

Take a look at the following example:

function f () {    alert (x);} Function F1 () {    var x = 1;    f ();} function F2 () {    var x = 1;    f ();} F1 (); F2 ();

If there is a dynamic scope, then the result should be 1, 2, but the end result is not what we want, and the result is: x isn't defined. So JavaScript doesn't have a dynamic scope.

Lexical scopes (also known as static scopes)

We can declare a x=100 at the front of the function

var x=100;function f () {    alert (x);} Function F1 () {    var x = 1;    f ();} function F2 () {    var x = 1;    f ();} F1 (); F2 ();

The results were popped two times 100. Describes the scope of JavaScript as a static scope, which analyzes:

function f () {    alert (x);} f [[scope]]  = = LE = =  window//Create a Scope object F [[scope]], It is equal to the lexical environment at the time of Creation Le (according to the previous knowledge we can also know that at this time the lexical environment equals window) function F1 () {    var x = 1;    f ();//Real Execution (step by step) LE  ->f.[[scope]]  = =  Window}

In the lexical parsing phase, the relevant scopes have been identified. The scope also forms a related chain, which we call the scope chain. Take a look at the following example:

function f () {    //f.scope = = Window    var x = 100;//f.le = = {x:100,g: function}        var g = function () {//g.scope = F.le                A Lert (x);    }    g ();//In the implementation of G, the first to find G.scope, no words to find f.le, have no words to find f.scope ... Keep looking up. Window    }f ();

The end result is: 100
Take a look at a classic example:

Defines the global variable color, which is applicable globally, where global variables colorvar color = "Red" can be used everywhere, function ChangeColor () {//in ChangeColor ()        The function internally defines the local variable anothercolor, only valid in function ChangeColor () var anothercolor = "Blue";        function Swapcolor () {//within the Swapcolor () function defines the local variable tempcolor, only valid in function Swapcolor () var tempcolor = Anothercolor;        Anothercolor = color;                color = Tempcolor;                You can access color, Anothercolor, and Tempcolor console.log (color) here;        Blue Console.log (Anothercolor);            Red Console.log (Tempcolor);    Blue} swapcolor ();                Only color can be accessed here, Anothercolor, Tempcolor console.log (color) cannot be accessed;        Blue Console.log (Anothercolor);            Anothercolor is not defined Console.log (Tempcolor);                Tempcolor is not defined}changecolor ();//This can only be accessed colorconsole.log (color);        Blueconsole.log (Anothercolor);            Anothercolor is not definedconsole.log (Tempcolor); Tempcolor is not defined

It is also important to note that the new function does not have the same situation

var x= 123;function F () {    var x = +;    G.[[scope]]  = = Window    var g = new Function ("", "alert (x)");    g ();} f ();//The result is: 123

Summary:

Take f1{f2{X} as an example, to want X, first in the function inside the lexical environment to find, have not found to go to the parent function of the lexical environment to find ... Go to the Window object and look inside.
At this time, the problem came ....

Question 1: Here it seems that if there are multiple functions want a variable, each time to write a good trouble ah, we have any way to lazy?

Method: Set the variable to a global variable

Question 2: Does it mean reducing the use of global usage? Because in our big project when inevitably to introduce a number of JS library, the name of the variable between the possible conflict, and error after difficult to find, this time we how to do?

Method: Set the variable in a hit function, such as the following:

function () {    var a = 1;    var b = 2;    function f () {        alert (a);    }}



3: According to your method, we can not access the outside, how to do?

Method: We use the anonymous function method, the example is as follows:

(function () {    var a = 1,        b = 2;    function f () {        alert (a);    }    WINDOW.F = f;}) (); F ();//The result is: 1

JS interview pit: Variable boost

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.