参考原文: 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);