在函数上执行 setTimeout 时出现问题 - 将其作为参数传递

发布于 2024-09-15 19:49:30 字数 213 浏览 8 评论 0原文

大家好,我有一个函数接受 this 作为参数 - 'this' 指的是 dom 元素,单击该元素后应该运行一个函数。问题是,我希望在一小段延迟后调用此函数,但是传递变量项 this 不起作用,因为当执行函数“this”时,则不会不是指传入参数中的对象,而是指窗口对象。

我怎样才能完成这件事?

Hi guys I have a function which accepts this as a parameter - 'this' referring to the dom element which upon clicked should run a function. The thing is that I want this function to be called after a small delay however passing the variable term this doesn't work as when the function is executed 'this' then doesn't refer to the object in passed in the parameter but to the window object.

How can I get this done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过潦 2024-09-22 19:49:30

您可以捕获这个

var t = this;
window.setTimeout(function() {
    // use the t variable here
}, 2000);

You could capture this:

var t = this;
window.setTimeout(function() {
    // use the t variable here
}, 2000);
放手` 2024-09-22 19:49:30

PrototypeJS 将 bind() 方法添加到 函数.原型。此方法允许您将函数和参数绑定到特定对象的上下文。简而言之,

window.setTimeout((function() {
    alert(this);
}).bind(this), 2000);

最好的部分是,该方法现在已成为 ECMA-262 规范的一部分,JavaScript 正是基于该规范,并且本机实现正在推广到现代浏览器中。如果尚未实现,PrototypeJS 只会添加此方法。

我在 http://jsfiddle.net/rLpbx/ 处设置了一个示例脚本。

PrototypeJS adds the bind() method to Function.prototype. This method allows you to bind a function and arguments to the context of a particular object. Simply,

window.setTimeout((function() {
    alert(this);
}).bind(this), 2000);

The best part is that this method is now part of the ECMA-262 specification, which JavaScript is based upon, and native implementations are rolling out into modern browsers. PrototypeJS will only add this method if it's not already implemented.

I've set up an example script at http://jsfiddle.net/rLpbx/.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文