JavaScript scope

Foreword:

​ This is summed up by reading the blog of a big guy on github with his own understanding

作用域Refers to the area in the program source code where variables are defined

The scope determines how to find the variable, that is, the access rights of the currently executing code to the variable

JavaScript uses 词法作用域(lexical scoping) which is static scoping

static scope vs dynamic scope

Because JavaScript uses lexical scoping, the scope of a function is determined when the function is defined.

The opposite of lexical scope is dynamic scope

The scope of a function is determined when the function is called

var value = 1;

function foo() {
    console.log(value);
}

function bar() {
    var value = 2;
    foo();
}

bar();
//这里打印的是什么 1? 2?

static scope:

​ Execute the inner scope of the foo() function to find the value, can not find it in the global variable, find it and print out 1

dynamic scope

​ Execute the inner scope of the foo() function to find the value, can not find it, enter the calling function (bar) scope, find the value, print 2

Because js is static scope so here is 1

Refer here to "The Definitive Guide to JavaScript" P183

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f();
}
checkscope();

If you understand the static scope of JavaScript, you can easily judge that what is printed here is the 'local variable' local scope

So here we return a function object nested within the function instead of returning the result directly

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f;
}
checkscope()();

still "local scope"

The execution of JavaScript functions is used 作用域链. This scope chain is created when the function is defined. The nested function f() is defined on this scope chain, and the variable scope inside must be a local variable. No matter what the circumstances are, f() is executed. ) The binding of local variables is still valid, so the printout is still

local scope

The next article will use the execution context to interpret what is different about this code in operation

Guess you like

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