setTimeout的this问题

MDN这样描述:

 

在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或全局)对象。当使用类的方法时,需要 this 引用类的实例,你可能需要显式地把 this 绑定到回调函数以便继续使用实例。

function LateBloomer() {
  this.petalCount = Math.ceil(Math.random() * 12) + 1;
}

// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
  window.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'方法


我之前一直不太明白setTimeout的this既然指向window,为什么bind一下就指向obj对象了
后来忽然感觉想明白了,收到箭头函数的一点启发,好像是因为在定义的时候,this的确是指向obj对象的,这个时候可以使用this.xxx.bind(this)将xxx函数绑定到只指向obj对象,但是如果不绑定,等到
setTimeout函数执行的时候,this指向的就是window全局对象了。不知道自己这样理解对不对

posted on 2017-07-07 16:35  瓦蕾瓦蕾  阅读(107)  评论(0编辑  收藏  举报

导航