-
如何绑定this的取值
-
如何获取函数外层的this
一:首先解决如何绑定this取值:
比如下面代码:
const person = {
name:"thc",
age: 18,
test: function(){
console.log(this);
}
}
person.test();
const test = person.test;
test();
控制台输出:
可见
person.test(): 输出的是person的对象object
test():输出的是window
解决方法:绑定this取值,通常用bind进行绑定
修改后的代码例如:
const person = {
name:"thc",
age: 18,
test: function(){
console.log(this);
}
}
person.test();
const test = person.test.bind(person);
test();
控制台输出:
结论1:与大多语言不一样,在JavaScript中,函数里的this指向的是执行时的调用者,而非定义时所在的对象。
二:如何获取函数外层的this
还是从代码的角度去讲解,如下:
const person1 = {
test:function(){
setTimeout(function(){
console.log(this)
},1000);
}
};
person1.test(); // 输出window
//注释:setTimeout(func, time)表示time时间后执行func函数
从上述结果可以表明,函数输出的this是window,并没有输出person这个对象
解决方法:当我们需要去获取外层的this时,常用两种方法
第一种:在外层将this记录下来,例如:
const person1 = {
test:function(){
let outer = this
setTimeout(function(){
console.log(outer)
},1000);
}
};
person1.test(); // 输出{test: f}
第二种: 使用箭头函数,箭头函数不重新绑定this的取值,它会绑定上层的object,例如:
const person2 = {
test:function(){
setTimeout(() => {
console.log(this)
},1000);
}
};
person2.test(); // 输出{test:f}
结论二:箭头函数不重新绑定this的取值