[英]Issues with executing setTimeout on a function - passing this as a parameter
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. 嗨,大家好我有一个接受函数
this
作为一个参数- “ this
”指哪点击时要运行的函数的DOM元素。 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. 关键是我希望在一个小的延迟后调用此函数,但是传递变量项
this
不起作用,因为执行该函数时,“ this
”不引用传入参数的对象,而是引用该对象。窗口对象。
How can I get this done? 我该怎么做?
You could capture this
: 您可以捕获
this
:
var t = this;
window.setTimeout(function() {
// use the t variable here
}, 2000);
PrototypeJS adds the bind() method to Function.prototype . PrototypeJS将bind()方法添加到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. 最棒的是,此方法现在已成为ECMA-262规范的一部分,该规范基于JavaScript,并且本机实现已在现代浏览器中推广。 PrototypeJS will only add this method if it's not already implemented.
PrototypeJS仅在尚未实现时添加此方法。
I've set up an example script at http://jsfiddle.net/rLpbx/ . 我已经在http://jsfiddle.net/rLpbx/建立了一个示例脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.