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

<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>

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值