Understanding the prototype chain and the scope chain

// What is the scope chain:
        // scope chain is for variables, such as we have a function nested inside another function 1 2, so this time there are three scopes: global scope ---> 1 function scope ---> 2 scope function
        //, then the function within 2 will first find relevant variable in their effect, if there is no will look to their superiors scope, the search process is scope chain
        // Example 1:
      
 1   var a = 100
 2         function f1(){
 3             a = 10
 4             function f2(){
 5                 a = 1
 6                 console.log(a);   
 7             }
 8             f2()
 9         }
10         f1()

 

        // Example 1 final printed result is 1, because f2 function in their scope has found a variable a, so it will not continue to look up

        // What is the prototype chain it?
        // prototype chain is for the purposes of the constructor, when we create a function obj, new out through a variable a new function f3, then this new function will inherit some of the properties of obj function
        // When we use the variable is not defined in the new function, it will go to find the original function of this variable obj
        // Example 2:
       
 1  function obj(){
 2             this.name = '陈斌',
 3             this.age = 25
 4             obj.prototype.sex = '男'
 5         }
 6         let f3 = new obj()
 7         f3.salary = 6000
 8         console.log(f3.name); 
 9         console.log(f3.sex);
10         console.log(f3.salary);
11         console.log(f3.c);
12         

 

        // Example 2 outputs are: Chen Bin Male 6000 undefined
        // name, age, sex are the property obj function, salary is added to the new function f3 property, but when we used the variable is not defined in f3, it will automatically look to its parent function
        // when the parent does not function this variable, it will return an undefined

        

Guess you like

Origin www.cnblogs.com/1825224252qq/p/11775810.html