Js scope
To put the js scope in a more general way, the scope determines the access of the currently executing code to a variable
JavaScript uses lexical scoping, also known as static scoping.
Static and dynamic scopes
Static/lexical scope: The scope of a function is determined when the function is defined.
Dynamic scope: Lexical scope is the opposite of dynamic scope, where the scope of a function is determined at the time the function is called.
example
Let’s take a quick look at a chestnut:
var value = 1; function foo() { console.log(value); } function bar() { var value = 2; foo(); } bar(); // The result is...?Copy the code
Statically scoped analysis: foo looks for local variable value inside foo. If it doesn’t, it looks for the code level above foo based on where it was written. Value equals 1, so it prints 1.
Dynamically scoped analysis: Function foo is executed, still looking for local value from within foo. If not, the value variable is looked up from within the scope of the calling function, that is, the bar function, so the result prints 2.
Because JavaScript is static scoped, the result for this example is 1.
Bash is dynamic scope
Here are two more examples from the AUTHORITATIVE JS Guide:
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
checkscope();
Copy the code
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f;
}
checkscope()();
Copy the code
So what is the output of this code?
Because JavaScript is lexical, functions are scoped based on where they are created.
So both answers are “local scope”;
So let’s think about it a little bit more, is there any difference between the two ends of the code?
Given what we learned about the execution context in the previous article, the execution context of the two pieces of code is different.
Let’s simulate the first code :(the two functions are pushed one by one on the stack before being executed)
ECStack.push(<checkscope> functionContext);
ECStack.push(<f> functionContext);
ECStack.pop();
ECStack.pop();
Copy the code
Let’s simulate the second code :(execute the second function after the first function is pushed onto the execution stack after the execution context is popped)
ECStack.push(<checkscope> functionContext);
ECStack.pop();
ECStack.push(<f> functionContext);
ECStack.pop();
Copy the code
The answer, to quote the Definitive JavaScript Guide, is:
JavaScript functions are executed using the scope chain, which is created when the function is defined. The nested function f() is defined in the scope chain, where the variable scope must be a local variable. This binding remains in effect when f() is executed, no matter where or when f() is executed.
This article is quoted in the following links, if there is infringement contact author can be deleted
Github.com/mqyqingfeng… Github.com/mqyqingfeng…