I have difficulties with using the this keyword in a MooTools (1.3) class. The constructor assigns a value to an attribute, and a subsequently run method displays this value in an alert popup. If I want to run this method delayed (using myfunction.delay(…)) the popup displays 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.
When we call
delayon a function, that function will be executed in the context of the global object (usuallywindow). The solution is to wrap it inside another function and capture the objectmin the closure.An easier way to doing this is to use the
bindparameter in the call todelay. The bind parameter specifies what thethisvalue should refer to inside the function when it is invoked.