JS-scope and closure
1 knowledge points
1.1 execution context
- The scope of execution context: ① a script (global); ② a function
- In the scope of "global" or "function", the following variables will be promoted
global: variable definition, function declaration
function: variable definition, function declaration, this, arguments
(PS: pay attention to the difference between "function declaration" and "function expression")
1.2 this
The value of this can only be confirmed when it is executed, and cannot be confirmed when it is defined.
————————————————
*Executed as a constructor
* Executed as an object attribute
* Executed as an ordinary function
*call apply bind ( difference? )
1.3 Scope
Scope features:
*No block-level scope
*Only function and global scope
// 无块级作用域
if (true) {
var name = 'zhangsan'
}
console.log(name) // zhangsan
// 函数和全局作用域
var a = 100;
function fn() {
var a = 200;
console.log('fn',a)
}
console.log('global', a) // global 100
fn() // fn 200
1.4 Scope chain
Free variables: Variables that are not defined in the current scope.
Scope chain-variable definitions that cannot be found in the current scope will be found in the parent scope
1.5 Closure
How to implement closures?
*Function as return value
*Function as parameter
2 Q&A
Topic:
*Talk about the understanding of variable promotion
* Explain several different usage scenarios of this
Small extension: What is the difference between call, apply, and this? scenes to be used?
*Create 10 a tags, the corresponding serial number will pop up when clicked
*How to understand the scope
*Application of closure in actual development
2.1 Talk about the understanding of variable promotion
The following 2 will be executed in advance
*variable definition
*function declaration (note the difference with function expression)
2.2 Explain several different usage scenarios of this
this represents the current object, and the direction of this is determined according to the context of the call.
The context of the call includes global & local.
- Global environment-point to the window object
- Local environment-
① (ordinary function) global environment directly calls the function, this points to window
② (object function) object function call, which function calls this refers to which object
③ (constructor) uses new to instantiate the object, in the constructor The this points to the instantiated object
④ (call, apply) Use call or apply to change the point of this
Small extension: What is the difference between call, apply and this? scenes to be used?
Difference
1) Same:
call, apply, bind can modify the this point of a function to the first parameter passed in these three methods,
2) different:
call, apply will be executed immediately, and bind returns a Function, need to be called and then executed.
The second parameter is the parameter passed in to the method to be executed, call and bind are passed parameters independently, and apply is passed parameters in an arrayApplication scenarios
1.
When the this point of a function needs to be changed 2. Call can be used when there are fewer parameters, and more parameters can be passed in an array using apply
3. When repeated calls are required, a new method can be defined using bind
var obj={
name:'Li lei',
intr:function( age, city ){
console.log(`我叫${
this.name},我${
age}岁,我来自${
city}`);
}
}
var obj2={
name:'Han meimei',
intr:function( age, city ){
console.log(`I'm ${
this.name},I'm ${
age} years old,I'm from ${
city}`);
}
}
obj.intr.call( obj2, 20, '中国' ); //我叫Han meimei,我20岁,我来自中国
obj.intr.apply( obj2, [ 20, '中国' ] ); //我叫Han meimei,我20岁,我来自中国
obj.intr.bind( obj2, 20, '中国' )(); //我叫Han meimei,我20岁,我来自中国
2.3 Create 10 a tags, when clicked, the corresponding serial number will pop up
var i
for (i=0; i<10; i++) {
(function (i) {
var a = document.createElement('a')
a.innerHTML = i + '<br>'
a.addEventListener('click', function(e) {
e.preventDefault( )
alert(i)
})
document.body.appendChild(a)
}) (i)
}
2.4 How to understand scope
Free variables: Variables that are not defined in the
current scope. Variable definitions that cannot be found in the current scope will be searched for the parent scope.
Scope chain-the process of searching upward for free variables
2.5 Application of closures in actual development
- isFirstLoad example (determine whether a value appears for the first time)
- The function of closure
1. Protect the properties of the object from being modified externally.
Only function b in function a can be accessed, and cannot be accessed through other means, so the security of i is protected.
2. Maintain certain variables in memory. It will not be automatically cleared after f1 is called. - What is a closure?
A function that can read the internal variables of other functions is a closure.
Closure is a bridge that connects the inside of the function and the outside of the function - Disadvantages
of closures Abuse of closures can cause memory leaks, because the variables defined in the wrapper function referenced in the closure will never be released,
so we should release the closure function in time when necessary. - Solution
obj = new Fname();
obj=null; //清空对象
clearInterval(timer) //清除计时器
dom.οnclick=null //指定为null
dom.addEventListener('click',fn,!1) //绑定方法
dom.removeEventListener('click',fn,!1) //尽量不要用匿名函数绑定,我们解绑事件时也好处理
dom.attachEvent ('onclick',fn); //绑定
dom.detachEvent('onclick',fn); //解除绑定