简体   繁体   English

在setTimeout上使用Apply / call而不是bind

[英]Using apply/call instead of bind on setTimeout

I've been working with asynchronous functions 我一直在使用异步功能

I've finally got around to avoid var _this = this; 我终于避开了var _this = this; and switched to actually using call/apply . 并切换为实际使用call/apply However when doing this, 但是,这样做时

/* inside instantiated obj */
setTimeout(function(){ 
  /* more code here */ 
}.apply(this), 0);

,does not launch an error and seems to work. ,则不会启动错误,并且似乎可以正常工作。 Why? 为什么? Because I recently noticed that it was "wrong" and should actually be: 因为我最近注意到它是“错误的”,实际上应该是:

/* inside instantiated obj */
setTimeout(function(){ 
  /* more code here */ 
}.bind(this), 0);

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

When you call apply or call methods on a function object, they will be invoked immediately and only the result is passed to the setTimeout . 当您在函数对象上调用applycall方法时, 它们将立即被调用,并且仅将结果传递给setTimeout

But bind returns a new function object and that will be invoked after the timeout elapses. 但是bind返回一个新的函数对象,该对象将在超时后被调用。

Since the timeout is set to 0, both the setTimeout s wait only 0 milliseconds and so you don't see any difference. 由于超时设置为0,因此setTimeout都仅等待0毫秒,因此您看不到任何差异。


You can use this example to understand it better. 您可以使用此示例来更好地理解它。

console.log(new Date());

setTimeout(function () {
    console.log("Apply", new Date());
}.apply(this), 3000);

setTimeout(function () {
    console.log("Bind", new Date());
}.bind(this), 3000);

You should be able to observe 3 seconds difference between Bind 's and the other two. 您应该能够观察到Bind和其他两个之间的3秒差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM