Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Scope and closures in js are described in detail

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "A detailed introduction of scopes and closures in js". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the detailed introduction of scopes and closures in js.

Scope

There are two scopes in JS: global scope | Local scope

Chestnut 1

Console.log (name); / / undefinedvar name = 'Ponyo'; var like = 'Sosuke' console.log (name); / / Ponyo function fun () {console.log (name); / / Ponyo console.log (eat) / / ReferenceError: eat is not defined (function () {console.log (like) / / Zosuke var eat = 'meat'}) ()} fun ()

1. Name is defined globally and can be accessed globally, so (2) Printing can print correctly.

two。 In the function fun, if the name attribute is not defined, it will be found in its parent scope, so (3) can also print 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 to unidirectional transparency, this is the domain chain, so (4) no and (5) can.

So the question is why the first print is "undefined" instead of "ReferenceError: name is not defined". The simple principle is the variable improvement of JS.

Variable promotion: when JS parses the code, it advances all declarations to the front of its scope

Chestnut 2

Console.log (name); / / undefinedvar name = 'Ponyo'; console.log (name); / / Ponyo function fun () {console.log (name) / / undefined console.log (like) / / undefinedvar name = 'Big Watermelon'; var like = 'Sosuke'} fun ()

Equivalent to

Var name;console.log (name); / / undefinedname = 'Ponyo'; console.log (name); / / Ponyo function fun () {var name; var like; console.log (name) / / undefined console.log (like) / / undefinedname = 'Big Watermelon'; like = 'console.log (name) / / Big Watermelon console.log (like) / / Sosuke} fun ()

Note: advance to the front of the current scope

Chestnut 3

PrintName (); / / printName is not a functionvar printName = function () {console.log ('Ponyo')} printName (); / / Ponyo

Equivalent to

Var printName;printName (); / / printName is not a functionprintName = function () {console.log ('Ponyo')} printName (); / / Ponyo

It is easy to understand that a function expression is just a variable when it is declared.

Chestnut 4

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

As can be seen from the chestnut above, we should not rashly think that the scope of variables declared by var in JS is the starting and ending scope of curly braces, ES5 does not have block-level scope, in essence, it is a function scope; after the definition of let and const in ES6, there is 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 advanced, but because the judgment condition is no, so the function body is not executed. So "TypeError: print is not a function" appears. While,switch,for is the same.

Closure

The function and the reference to its state, the lexical context (lexical environment), form a closure (closure). That is, closures allow you to access the scope of an external function from an internal function. In JavaScript, a function generates a closure each time it is created.

The above definition comes from MDN. To put it simply, a closure is a function that has access to variables in the scope of another function.

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

/ / for example, function makeFunc () {var name = "Ponyo"; function displayName () {console.log (name);} return displayName;} var myFunc = makeFunc (); myFunc ()

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

In the example, myFunc is a reference to the instance of the displayName function created when makeFunc is executed, while the instance of displayName still has access to variables in its lexical scope, that is, to 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 closures is to create one function inside another

● usually, the scope of a function and all its variables are destroyed at the end of function execution. However, after you create a closure, the scope of the function is saved until the closure does not exist

/ / case II function makeAdder (x) {return function (y) {return x + y;} var add5 = makeAdder (5); var add10 = makeAdder (10); console.log (add5 (2)); / / 7console.log (add10 (2)); / / 12pm / release the reference to the closure add5 = null;add10 = null

In essence, makeAdder is a function factory-it creates a function that adds the specified value to its parameters. In the above example, we used the function factory to create two new functions-one summing its parameters to 5 and the other to 10.

Both add5 and add10 are closures. They share the same function definition, but preserve different lexical environments. In an add5 environment, x is 5. In add10, x is 10.

The scope chain of a closure contains its own scope, as well as the scope and global scope of the function that contains it.

The ● closure can only get the last value of any variable in the containing function.

/ / Chestnut 1function arrFun1 () {var arr = []; for (var I = 0; I < 10; iTunes +) {arr [I] = function () {return I}} return arr} console.log (arrFun1 () [9] ()); / / 10console.log (arrFun1 () [1] ()); / / 10 hand / Chestnut 2function arrFun2 () {var arr = []; for (var I = 0) I < 10; iTunes +) {arr [I] = function (num) {return function () {return num};} (I)} return arr} console.log (arrFun2 () [9] ()); / / 9console.log (arrFun2 () [1] ()); / / 1

In Chestnut 1, the arr array contains 10 anonymous functions, each of which can access the external variable I. after arrFun1 is executed, its scope is destroyed, but its variable is still in memory and can be accessed by anonymous functions in the loop.

In Chestnut 2, there is an anonymous function in the arr array, and there are anonymous functions in the anonymous function. The num accessed by the innermost anonymous function is saved in memory by the higher-level anonymous function, so you can access the value of I each time.

At this point, I believe you have a deeper understanding of the "detailed introduction of scopes and closures in js". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report