<span style="font-size:18px;">//this的指向问题简介
//改写成class
class obj{
constructor(){
this.name = "zxh"; //必须要有this,this为当前的对象
this.age = 12;
}
say(){
console.log(this.name+" "+this.age);
}
}
class animals{
constructor(){
this.name = "gou";
this.age = 23;
}
says(say){
setTimeout(function(){
console.debug(this.name+" "+this.age+" "+say); //这里的this指向存在问题,:undefined undefined hahah
},100);
}
}
var ss = new animals();
ss.says("hahah");
//解决这的bug问题
//1、第一种方式,将this修改为animals,因为当前的this定义时是在当前对象,但是使用是在窗体对象,也就是全局对象中,所以this指向的不同
class animals{
constructor(){
this.name = "gou";
this.age = 23;
}
says(say){
setTimeout(function(){
console.debug(animals.name+" "+animals.age+" "+say);
},100);
}
}
var ss = new animals();
ss.says("hahah");
//2、第二种方式,通过将copy this 实现指针指向当前的对象
class animals{
constructor(){
this.name = "gou";
this.age = 23;
}
says(say){
let thisCopy = this;
setTimeout(function(){
console.debug(thisCopy.name+" "+thisCopy.age+" "+say);
},100);
}
}
var ss = new animals();
ss.says("hahah");
//3、第三种方式,通过bind(this)实现
class animals{
constructor(){
this.name = "gou";
this.age = 23;
}
says(say){
let thisCopy = this;
setTimeout(function(){
console.debug(this.name+" "+this.age+" "+say);
}.bind(this),100);
}
}
var ss = new animals();
ss.says("hahah");
//4、第四种,通过es6 arrow实现,因为箭头函数时定义函数时和执行函数时都是指向的当前对象
class animals{
constructor(){
this.name = "zxh";
this.age = 21;
}
says(say){
setTimeout(()=>{
console.log(this.name+" "+this.age+" "+say);
},100);
}
}
var ss = new animals();
ss.says("hahah");</span>
js中的this指向问题及解决方案
最新推荐文章于 2023-09-04 21:13:08 发布