javascript之如何将 "this"传递给 setTimeout 回调
你猜
阅读:20
2025-01-19 22:14:33
评论:0
代码:
<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>
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。