在函数中,this指向当前函数的作用域,this
的值在函数被调用的时候才会指定。
我如果在类中写了一个
class A{
private a:number=0;
private b:number=0;
public testFun(){
this.a=this.b=10;
}
}
这里的this就是类A的一个对象,可以正确的修改对象的a与b值
而如果是这样:你觉得是输出是5还是10?
class A{
private a:number=0;
private b:number=0;
public testFun(){
this.a=this.b=10;
let b:B=new B();
b.callFun(this.testFun2);
}
public testFun2(){
console.log(this.a);
}
}
class B{
private a:number=5;
public callFun(cb:Function){
cb();
}
}
最后console输出的即不是10也不是5,
当你将一个函数传递到某个库函数里稍后会被调用时。 因为当回调被调用的时候,它们会被当成一个普通函数调用, this
将为undefined
【顶级的非方法式调用会将 this
视为window
。 (在严格模式下, this
为undefined
而不是window】
所以输出语句就变成了console.log(window.a),a未定义,输出undefined
所以在工作中,通常在将函数作参数传递时,要将this绑定到函数上
方法有两种
1.使用bind方法,参数即为作用域,如可以将上面的调用改成:
b.callFun(this.testFun2.bind(this));
2.使用箭头函数()=>{},箭头函数能保存函数创建时的 this
值,相当于自动绑定this
b.callFun(()=>{this.testFun2()});也是一样的
这样console就会输出10了