我怎样才能通过“;这个“;进入setTimeout回调

How can I pass "this" into setTimeout callback?

本文关键字:这个 setTimeout 回调 进入      更新时间:2023-09-26

fiddle

代码:

<button onclick="this.disabled=true; setTimeout(function(){this.disabled=false;},500);">click</button>

this似乎指的是窗口而不是按钮。如何传入按钮对象以便重新启用它?

我知道变通办法。。。我可以给按钮一个ID,然后再抓住它,但我很想知道我是否能以某种方式将this传入。

this是由函数的调用方式定义的。

foo.someFunc(); /* this is foo */
foo.bar.someFunc(); /* this is bar */
window.someFunc(); /* this is window */
someFunc(); /* this is window because window is the default */
setTimeout(foo.bar.someFunc, 500); /* this is window because you've passed a function and disassociated it from foo.bar */

如果你想在函数之间传递它,你必须将它复制到另一个变量中。

<button onclick="this.disabled=true; var that = this; setTimeout(function(){that.disabled=false;},500);">click</button>

您可以通过绑定函数来显式设置函数的上下文。

<button onclick="
  this.disabled=true;
  setTimeout(
    function(){this.disabled=false}.bind(this),
    500)">click</button>

您会注意到禁用有效,只是启用无效。这是因为this不是局部变量;当事件处理程序触发时,它就有了正确的含义:不再绑定到按钮。

试试这个:

<button onclick="var self=this; self.disabled=true; setTimeout(function(){self.disabled=false;},500);">click</button>

顺便说一句,尽量避免像这样内联编写代码。为伟大的胜利编写合适的处理程序:

// HTML:
<button id="myBtn">click</button>
// JS:
window.onload = function() {
   document.getElementById('myBtn').addEventListener("click", function() {
      var self = this;
      self.disabled = true;
      setTimeout(function() {
          self.disabled = false;
      }, 500);
   }, false);
}

是的,更详细,但最终更易于维护。

jQuery让它变得更容易:

$(function() {
    $('#myBtn').click(function() {
      var self = this;
      self.disabled = true;
      setTimeout(function() {
          self.disabled = false;
      }, 500);
   });
});