[英]MooTools classes and `this` in delayed function calls
I have difficulties with using the this
keyword in a MooTools (1.3) class. 我在MooTools(1.3)类中使用
this
关键字时遇到了困难。 The constructor assigns a value to an attribute, and a subsequently run method displays this value in an alert
popup. 构造函数为属性分配值,随后运行的方法在
alert
弹出窗口中显示此值。 If I want to run this method delayed (using myfunction.delay(…)
) the popup displays undefined
. 如果我想延迟运行此方法(使用
myfunction.delay(…)
),弹出窗口将显示undefined
。
var MyClass = new Class({
initialize: function() {
this.x = 13;
},
run: function() {
alert(this.x);
}
});
window.addEvent('domready', function() {
var m = new MyClass();
m.run(); // ``13''
m.run.delay(2000); // ``undefined''
});
After fiddling around, I managed to find the following solution: 摆弄后,我设法找到以下解决方案:
window.addEvent('domready', function() {
var m = new MyClass();
(function() { m.run() }).delay(2000); // ``13''
});
Still, I would like to understand what's happening here, and why simply calling m.run.delay(…)
doesn't do the trick. 不过,我想了解这里发生了什么,以及为什么简单地调用
m.run.delay(…)
并不能解决问题。
When we call delay
on a function, that function will be executed in the context of the global object (usually window
). 当我们在函数上调用
delay
时,该函数将在全局对象(通常是window
)的上下文中执行。 The solution is to wrap it inside another function and capture the object m
in the closure. 解决方案是将其包装在另一个函数中并捕获闭包中的对象
m
。
An easier way to doing this is to use the bind
parameter in the call to delay
. 更简单的方法是在调用中使用
bind
参数来delay
。 The bind parameter specifies what the this
value should refer to inside the function when it is invoked. bind参数指定在调用函数时
this
值应在函数内引用的内容。
m.run.delay(2000, m);
When you invoke a function as m.run()
the this
keyword will refer to the base object m
. 当您将函数调用为
m.run()
, this
关键字将引用基础对象m
。 Function.prototype.delay
however probably uses setTimeout
to invoke your delayed function. 但是,
Function.prototype.delay
可能使用setTimeout
来调用延迟函数。
Function.prototype.delay = function(ms) {
setTimeout(this, ms);
}
The problem with this form is that setTimeout
will invoke your function without the base object reference, so this
will refer to the global object (~ window ). 这种形式的问题是
setTimeout
将在没有基础对象引用的情况下调用您的函数,因此this
将引用全局对象(~ window )。
The solution is to pass the object of invocation to delay
explicitly. 解决方案是将调用对象传递给显式
delay
。
/**
* delay - (number) The duration to wait (in milliseconds).
* bind - (object, optional) The object that the "this" of the function
* will refer to.
* args - (mixed, optional) The arguments passed (must be an array if the
* arguments are greater than one).
*/
m.run.delay(2000, m);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.