Home>Article>Web Front-end> Detailed explanation of js scope and closure

Detailed explanation of js scope and closure

Robert De Niro
Robert De Niro forward
2019-11-29 14:02:02 2649browse

Detailed explanation of js scope and closure

Scope

There are two types of scope in JS: global scope|local scope

Lizi 1

console.log(name); //undefined var name = '波妞'; var like = '宗介' console.log(name); //波妞 function fun(){ console.log(name); //波妞 console.log(eat) //ReferenceError: eat is not defined (function(){ console.log(like) //宗介 var eat = '肉' })() } fun();

[Related course recommendations:JavaScript Video Tutorial]

1. The name is defined globally and can be accessed globally, so (2) Printing can be printed correctly;

2. In function fun, if the name attribute is not defined, it will be found in its parent scope, so (3) can also be printed correctly.

3. The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions of the internal environment. Similar toOne-way transparency, this is a scope chain, so (4) is not possible but (5) is.

Then the question arises, why the first print is "undefined" instead of "ReferenceError: name is not defined". The principle is simply thevariable promotion of JS

Variable promotion:When JS parses the code, it will advance all declarations to the front of the scope


Chestnut 2

console.log(name); //undefined var name = '波妞'; console.log(name); //波妞 function fun(){ console.log(name) //undefined console.log(like) //undefined var name = '大西瓜'; var like = '宗介' } fun();

is equivalent to

var name; console.log(name); //undefined name = '波妞'; console.log(name); //波妞 function fun(){ var name; var like; console.log(name) //undefined console.log(like) //undefined name = '大西瓜'; like = '宗介' console.log(name) //大西瓜 console.log(like) //宗介 } fun();

Note:is advanced to the current scope The front


Chestnut 3

printName(); //printName is not a function var printName = function(){ console.log('波妞') } printName(); //波妞

is equivalent to

var printName; printName(); //printName is not a function printName = function(){ console.log('波妞') } printName(); //波妞

This way it is easy to understand, the function expression is in When declared, it is just a variable


Chestnut 4

{ var name = '波妞'; } console.log(name) //波妞 (function(){ var name = '波妞'; })() console.log(name) //ReferenceError: name is not defined { let name = '波妞'; } console.log(name) //ReferenceError: name is not defined

As can be seen from the above chestnut, variables declared by var in JS cannot be hastily considered The scope of is the starting and ending scope of the curly braces. ES5 does not have a block-level scope, but is essentially a function scope. Only after the let and const definitions were introduced in ES6, there was a block-level scope.


Chestnut 5

function p1() { console.log(1); } function p2() { console.log(2); } (function () { if (false) { function p1() { console.log(3); } }else{ function p2(){ console.log(4) } } p2(); p1() })(); //4 //TypeError: print is not a function

This is a very classic chestnut. The declaration is made in advance, but because the judgment condition is no, the function body is not executed. So "TypeError: print is not a function" will appear. The same applies to while, switch, and for

closure

The function and the reference to its state, that is, the lexical environment (lexical environment) together form a closure. ). That is, closures allow you to access the outer function scope from the inner function. In JavaScript, functions generate closures every time they are created.

The above definition comes from MDN. Simply put, a closure refers to a function that has the right to access variables in the scope of another function.


● The key to closure is that its variable object should have been destroyed after the external function is called, but the existence of the closure allows us to still access the variable object of the external function.,

//举个例子 function makeFunc() { var name = "波妞"; function displayName() { console.log(name); } return displayName; } var myFunc = makeFunc(); myFunc();

Functions in JavaScript form closures. A closure is composed of a function and the lexical environment that creates the function. This environment contains all local variables that can be accessed when this closure is created

In the example, myFunc is a reference to the displayName function instance created when makeFunc is executed, and the displayName instance can still access its lexical Variables in the scope can access name. Thus, when myFunc is called, name can still be accessed, and its value 'Ponyo' is passed to console.log.The most common way to create a closure is to create another function inside a function


● Usually, the scope of a function and all its variables will end at the end of function execution was later destroyed. However, after creating a closure, the scope of the function will be saved until the closure no longer exists

//例二 function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 //释放对闭包的引用 add5 = null; add10 = null;

Essentially, makeAdder is a function factory - he creates the A function that adds the sum of a specified value and its arguments. In the example above, we used the function factory to create two new functions—one that sums its arguments plus 5 and another that sums 10 .

add5 and add10 are both closures. They share the same function definition, but store different lexical environments. In the context of add5, x is 5. And in add10, x is 10.

The scope chain of a closure includes its own scope, as well as the scope of the containing function and the global scope.


● Closure can only obtain the last value of any variable in the containing function

//栗子1 function arrFun1(){ var arr = []; for(var i = 0 ; i < 10 ; i++){ arr[i] = function(){ return i } } return arr } console.log(arrFun1()[9]()); //10 console.log(arrFun1()[1]()); //10 //栗子2 function arrFun2(){ var arr = []; for(var i = 0 ; i < 10 ; i++){ arr[i] = function(num){ return function(){ return num }; }(i) } return arr } console.log(arrFun2()[9]()); //9 console.log(arrFun2()[1]()); //1

In example 1, the arr array contains 10 Each anonymous function can access the external variable i. After arrFun1 is executed, its scope is destroyed, but its variables still exist in memory and can be accessed by anonymous functions in the loop. In this case, i is 10;

In Chestnut 2, there is an anonymous function in the arr array, and there are anonymous functions within the anonymous function. The num accessed by the innermost anonymous function is saved in the memory by the upper-level anonymous function, so it can be accessed. to the value of i each time.

This article comes from thejs tutorialcolumn, welcome to learn!

The above is the detailed content of Detailed explanation of js scope and closure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete