解析javascript里 setTimeout里 this的指向,并用bind改变其this指向

本文探讨了JavaScript中setTimeout函数中this的指向问题。通过示例代码展示了为何需要使用bind来改变this的指向,以确保能正确访问到对象的属性。解释了不加bind时this默认指向window,而使用bind则可以将this绑定到指定的对象,确保方法的正确执行。
摘要由CSDN通过智能技术生成

参考原文: https://www.jianshu.com/p/ee175cade48b

先来看一段代码:

var lateBloomer = function(){
    this.petalCount = 1;
}
lateBloomer.prototype.bloom = function(){
    setTimeout(this.decaler.bind(this),1000);
}
lateBloomer.prototype.decaler = function(){
    console.log(`I am a flower with ${this.petalCount} petal`);
}

var flower = new lateBloomer();
flower.bloom();   //打印出 I am a flower with 1 petal

奇怪,为啥要这样写: setTimeout(this.decaler.bind(this),1000);

那以下的写法可以实现吗

1.  setTimeout(this.decaler,1000);

2.  setTimeout(this.decaler(),1000);

3.  setTimeout(function(){ 
        this.decaler() 
    }.bind(this),1000);
    
4.  setTimeout(function(){ 
        this.decaler() 
    },1000);

感兴趣的童鞋可以自己试试看哈

下面解析并发布结果:
1.setTimeout(this.decaler,1000);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值