[[scope]]:Every javascript function is an object, and there are some attributes in the object that we It can be accessed, but some cannot. These properties are only accessible to the JavaScript engine, and [[scope]] is one of them.
[[scope]] refers to what we call the scope, which stores the collection of runtime contexts. Runtime context: When a function is executed, an internal object called an execution context is created. An execution context defines the environment when a function is executed. The corresponding execution context is unique each time the function is executed, so Calling a function multiple times will result in the creation of multiple execution contexts. When the function completes execution, the execution context it generated will be destroyed.
Scope chain: A collection of execution context objects stored in [[scope]]. This collection is connected in a chain. We call this chain link a scope.
function a(){ function b(){ function c(){ } } }
a defined a.[[scope]] ===> 0: GO
a doing a.[[scope]] ===> 0: aAO
GO
b defined b.[[scope]] ===> 0: aAO
1:GO
b defined b.[[ scope]] ==
##c defined c.[[scope]] ===> 0 : bao 1: AAO 2: GO## C Defined c. [[scope]] === & gt :bAO
When the inner function is saved to the outside, a closure will be generated. Package will cause the original scope chain not to be released, causing memory leaks.
function a(){ function b(){ var bbb = 234; console.log(aaa); } var aaa = 123; return b; } var glob = 100; var demo = a(); demo();
Immediate execution function
Immediate execution function, for the function of initialization function, 1.(function(){}()); (w3c recommends the first type)2. (function () {}) ();
Only expressions can be executed. Symbolic execution
is executed immediately. Symbolic execution The function cannot be used again after the function expression
The function can be converted into a function expression through the plus sign, minus sign, etc. /-/! function test(){
console.log('a');
}
function test(){ var arr = []; for(var i = 0;i < 10;i ++){ (function (j){ arr[j] = function(){ document.write(j+' '); } }(i)); } return arr; } var myarr = test(); for(var i = 0;i < 10;i ++){ myarr[i](); }
The output result is: 1 2 3 4 5 6 7 8 9
Related articles:
Detailed explanation of JavaScript scope and closure Scope chain and closure in JavaScriptRelated videos:
JS Advanced Scope-Yan Shiba Javascript Advanced Video TutorialThe above is the detailed content of Detailed explanation of scope + closure in Javascript. For more information, please follow other related articles on the PHP Chinese website!