Js core -------- scope chain understanding, js core --------
Recently, the company had few things, so it took me a morning to learn about js function scopes, read a lot of information, and write some simple demos for verification and learning, next, I will share with you the results of my previous morning on the scope chain:
When defining a function (note that it starts when it is defined), it actually saves a scope chain.
When this function is called, it creates a new object to store its parameters or local variables, and adds the object to the scope chain, at the same time, create a new longer "chain" that represents the function call scope ".
For nested functions, the situation has changed: each time an external function is called, the internal function is redefined. Because each time an external function is called, The scope chain is different. Each time an internal function is defined, it requires a subtle difference-the code of the internal function is the same each time an external function is called, And the scope chain associated with this code is also different.
To learn this knowledge, we need to draw inferences from each other. In fact, many basic problems of js are related to the scope chain, including scope, execution environment, activity object, and closure. Let's look at the following example:
Function a () {var I = 0; function B () {alert (++ I);} return B;} var c = a (); c ();
At this point, the steps from definition to execution of function a are completed. At this time, a returns the reference of function B to function c, and the scope chain of function B contains the reference to the activity object of function, that is to say, B can access all variables and functions defined in. Function B is referenced by Function c, and function B is dependent on function a. Therefore, function a is not recycled by GC after return.
In this way, I learned the new knowledge points of the scope chain and reviewed the old knowledge points. Very satisfied. In the afternoon, I can start coding happily.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.