您的位置:首页 > Web前端 > JavaScript

js中的this指向问题及解决方案

2016-10-16 00:16 781 查看
<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: