首先来看一段代码:
function LateBloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
setTimeout(this.declare.bind(this), 1000);
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
var flower = new LateBloomer();
flower.bloom(); // 一秒钟后, 调用'declare'方法
在bloom中,为什么要这样写呢?
this.declare.bind(this)
首先,这里的this指的是LateBloomer构造函数所要实例化的对象,即:
this.declare = function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
};
若这么写:
setTimeout( function() {
console.log('I am a beautiful flower with ' +
this.petalCount + ' petals!');
}, 1000);
setTimeout的回调函数内部的this指向的是window,但petalCount属性是属于LateBloomer的instance,所以要用bind把this的指向变回来。