Object-Oriented JavaScript and setTimeout
Here are two examples of how to use setTimeout in an object constructor with public methods added to the prototype. Functions called using setTimeout are executed in the scope of the window object, so the this keyword does not apply. In both of these examples, clicking on a link triggers an alert after a pause of two seconds. In the first example, the alert function and the setTimeout are both in a public method of the object instance. In the second example, the setTimeout is in one public method while the alert is in another.
Example 1
var myObject = function(myArgument) {
this.myProperty = myArgument;
this.myTrigger = document.getElementById('myLink');
this.init();
};
myObject.prototype.init = function() {
this.myProperty = 'New Value';
YAHOO.util.Event.addListener(this.myTrigger, 'click', this.myMethod, this);
};
myObject.prototype.myMethod = function(e, obj) {
var myFunction = function() {
alert(obj.myProperty);
};
YAHOO.util.Event.preventDefault(e);
setTimeout(myFunction, 2000);
};
new myObject('Initial Value');
Example 2
var myObject = function(myArgument) {
this.myProperty = myArgument;
this.myTrigger = document.getElementById('myLink');
this.init();
};
myObject.prototype.init = function() {
this.myProperty = 'New Value';
YAHOO.util.Event.addListener(this.myTrigger, 'click', this.myMethod1, this);
};
myObject.prototype.myMethod1 = function(e, obj) {
YAHOO.util.Event.preventDefault(e);
setTimeout(function() { obj.myMethod2(); }, 2000);
};
myObject.prototype.myMethod2 = function() {
alert(this.myProperty);
};
new myObject('Initial Value');