Settimeout,bind和this [英] Settimeout, bind and this

查看:328
本文介绍了Settimeout,bind和this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里复制了MDN的代码片段: https ://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

Here I have copied code snippet from MDN : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

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();  
// after 1 second, triggers the 'declare' method

最令人困惑的部分是: window.setTimeout(this.declare.bind(this),1000);

The most confusing part is : window.setTimeout(this.declare.bind(this), 1000);

我明白如何这个有效,这个里面的settimeout总是绑定到全局对象。我知道可以有 var self var 在bloom函数中。

I understand how this works and this inside settimeout is always bound to global object.I know there can be var self or var that inside bloom function.

该行中有两个但是哪个这个指的是什么以及如何运作完全令人困惑。

There are two this in that line but which this refers to what and how that works is totally confusing.

如何运作?

推荐答案

首先阅读此链接。关于这个如何工作的非常好的解释。

First of all read this link. Very nice explanations about how this works.

.bind(this,args)只是帮助你在你的函数中传递这个上下文(因为在它里面,在你的例子中默认这个未定义或是指窗口)。

.bind(this, args) just help's you to pass your this context inside your function (because inside it, in your example by default this is undefined or refers to window).

另外 bind 是一个不错的选择:

Also bind is a nice alternative to this:

// Declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
  var self = this;
  window.setTimeout(self.declare, 1000);
};

作为 es6 中的最后一点你可以这样做:

And as the last point in es6 you can do it in this way:

window.setTimeout(() => {
  //do some stuff
}, 1000);

而不是

window.setTimeout(function () {
  //do some stuff
}.bind(this), 1000);

这让你不用考虑这个

这篇关于Settimeout,bind和this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆