scope and prototype chain in js

The scope is for variables. For example, if we create a function, and the function contains a function, then there are now three scopes.

  global scope ==> function1 scope ==> function2 scope

The characteristic of the scope is that you first look for it in your own variable scope, and if you can't find it, it will look up along the scope.

Such as:

var a = 1;
function b(){
    var a = 2;
    function c(){
        var a = 3;
        console.log(a);
    }
    c();
}
b();

The last print out is 3, because when the function c() is executed, it finds the variable a in its own scope, so it will not continue to search. If it is not found in the function c(), it will continue to search upwards. The global variable a will be found, and this search process is called the scope chain.

I don’t know if you have any doubts, why function c can look up variable a in function b, because function c is created in function b, that is to say, the scope of function c includes the scope of function b, and of course it also includes the scope of function b. Global scope, but function b cannot look up variables in function c because the scope only looks up.

So what is a prototype chain?

  The prototype chain is for constructors. For example, if I create a function first, and then pass a variable new to the function, the new function will inherit the properties of the created function, and then if I access the new function A certain property of this function, but I did not define this variable in the new function, then it will look up (to the function that created it), and the process of searching is called the prototype chain.

  Object ==> Constructor 1 ==> Constructor 2

  Just like inheritance in css, if it is not defined by itself, it will inherit the style of the parent element.

function a(){};
a.prototype.name = "Dream Chaser";
var b = new a();
console.log(b.name); //Dream Chaser

Guess you like

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