js chain scope

【Foreword】

There are a lot of js chain scopes introduced on the Internet, but they are very complicated and difficult to understand. Now I will organize a simple and easy-to-understand

 

【Details】

(1) Understand the premise of the chained scope of js 

  ① First of all, you must know the variable scope of js. There are two types of variable scopes of js: global and local 

  ②The current scope in js can access the variables and functions of its upper scope 

(2) Definition of js chained scope: 

  Description from The Definitive Guide to JS: 

      Functions in JavaScript run in the scope in which they are defined, not the scope in which they are executed. 

  This sentence is difficult to understand, but in a simple description, the chained scope of JS is: 

      When encountering the use of variable name or function name in JS, it will first look for the variable or function in the current scope. If it is not found, it will look for it in its upper scope, and so on. 

      The following example is quoted in many blog posts: 

var x = 10;  
function test() {  
    alert(x);  
}  
test();  

    The above example will prompt 10, which is easy to understand, because as mentioned above: the variables and functions in the upper object in js are visible to its child objects 

  Here's a slight twist on this example: 

var x = 10;  
function test() {  
    alert(x);  
    var x = 2;  
}  
test();  

    What is the value that the changed example pops up with? The answer is undefined, which is understood by the JS chained scope. When the function test is executed, it will first search in its own scope, and if x is defined in the function book, it will not search for the upper layer, but it is It is defined after the alert, so the alert will pop up undefined. If x is not defined in the function, as in the original example, it will be searched in its upper scope, which is 10 

 

 

 

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326096777&siteId=291194637