scope
-
Variable promotion — Design defects (variable overwriting, variable contamination) are avoided by the block-level scope let const
-
Scope: Controls the visibility and lifecycle of variables and functions
-
Es6 before:
-
Global scope
-
Function scope: Internal variables are destroyed after execution
function foo(){ for (var i = 0; i < 7; i++) { } console.log(i); } foo()
— > 7
How does ES6 support both variable promotion and block-level scope?
function test() {
var a = 1
let b = 2
{
let b = 3
var c = 4
let d = 5
console.log(b)
}
console.log(b)
console.log(c)
console.log(d)
}
test()
Copy the code
Function test() {console.log(a)} function demo() {var a = "test.log" test()} var a = "test.log" The lexical scope is determined during code compilation, Function demo() {var a = "出 出" function test() {console.log(a)} test() } var a = "demo" --> "demo"Copy the code
closure
Function 1 sets function 2, and function 2 can access variables in function 1, and when function 1 is finished, the accessed variables are not destroyed, but become closures for function 2 to access until function 2 is destroyed
Var innerFun = {function(){test1 = 1 const test2 = 2 var innerFun = {getName:function(){ console.log(test1) return myName }, SetName :function(newName){myName = newName}} return innerFun} var test = demo() test.setName(" ") test.getName() console.log(test.getName())Copy the code
this
Js the mechanism used to access internal properties of objects
This refers to the context in which the call is made
function foo(){
console.log(this)
}
foo() // window.foo()
--> this == window
Copy the code
Mechanism defects
-
The this in a nested function does not inherit from the outer function
-
_this = this
-
Arrow functions: do not create their own execution context, so this inherits this from the calling function
-
This in normal functions points to the global object Window by default
-
Call, bind, apply
-
Strict mode: This is undefined in the context of a function executed by default