When I first saw the terms “lexical scope” and “dynamic scope”, I was a little confused. I had only known global scope, functional scope and block-level scope, but I thought they were new concepts.
The lexical scope is the same as the static scope. It is defined when it is created, which means that TA is defined when we write code. JavaScript follows the lexical scope.
Dynamic scope is determined when it is called. They focus on different points, one on when to create and one on when to run.
Lexical scope
function m(){
console.log(a)
}
function n(){
var a = 97;
m();
}
var a = 1997;
n()
// 1997
Copy the code
Running the code above outputs 1997.
If function M wants to output the value of variable A, it will first look for the value in function M’s scope. If function M does not have the value in function M’s scope, it will look for the value in its upper scope.
If it was dynamically scoped, the output would be 97, whereas JavaScript follows lexical scoping, so we get 1997.
This implements “dynamic scope”
This is a JavaScript keyword that can achieve a similar effect to dynamic scoping. This object is automatically generated internally when a function is run. TA can only be used inside a function. The direction of this is not fixed, TA will change as the execution environment changes.
At first I thought “this” referred to window, and there should be many readers who think like me. Running the following code will show that this is not what we thought:
var obj = {
m: function m(){
console.log(this.msunh)
},
msunh : 97
}
var msunh = 1997;
var n = obj.m;
obj.m() // 97
n() //1997
Copy the code
If they all pointed to Window, the output should be 1997, but the actual result is different. This is because this refers to the environment in which the function is run, not the global object Window, but many usage scenarios refer to window. In the case of obj.m(), m() runs in obj, so this refers to obj; For n(), TA runs in the global environment, so this refers to the global environment Window, which is why TA’s results are different.
“Use strict” in strict mode
This refers to different objects in different situations.
1. In strict mode, this will retain the same value as when entering the execution environment, and this will default to undefined.function m() {"use strict";
returnthis; } m() // undefined 2. In the global execution environment, this refers to the global object Window, whether in strict mode or not. 3. When a function is called as a method on an object, this refers to the object on which the method was called. 4. The call() and apply() methods refer this to a specific object.Copy the code