later is better
I really enjoy hanging out at the YUI theater sometimes. There are very good conferences given mainly by the Yahoo! staff. I particularly like those one from Douglas Crockford, a Yahoo! JavaScript architect teach us very good stuff. In his “Advanced JavaScript” talk, he gives us a more OO solution to the setTimeout function. Let’s look at the later function code
The later function
var that = this;
var args = Array.prototype.slice.apply(arguments, [2]);
if (typeof method === "string") {
method = that[method];
}
setTimeout(function () {
method.apply(that, args);
}, msec);
return that;
};
Examples of use
say: function(what) {
alert(what);
},
shout: function(n, what) {
for (var i = 0; i < n; i++) {
this.say(what.toUpperCase());
}
}
};
duck.later(6000, "say", "Quack!").later(12000, "shout", 3, "Quack!");
Arguments [2..n] are the arguments to pass to the function
Since it extends Object itself, later will be available to every functions. That is a very bad idea to extend the Object prototype. Why? Because you don’t want to break code that is not yours, as with libraries or api. Looping over each properties of that Object is often the only way they have to accomplish their goal. We must never touch the Object prototype. I know, I b
reak my code using that later function with jQuery.
If you do not use any code that’s not yours, you can augment Object.prototype otherwise you’ll have to find another way not to break other’s code. In order to use later you could extend your own object depending on the pattern you use for programming JavaScript. The following is an example of how you could use it.
The later function in a simple pattern
Animal.prototype.later = function(msec, method) {
var that = this,
args = Array.prototype.slice.apply(arguments, [2]);
if (typeof method === "string") {
method = that[method];
}
setTimeout(function () {
method.apply(that, args);
}, msec);
return that;
};
Animal.prototype.say = function(what) {
alert(what);
};
Animal.prototype.shout = function(n, what) {
for (var i = 0; i < n; i++) {
this.say(what.toUpperCase());
}
};
duck = new Animal();
duck.later(6000, "say", "Quack!").later(12000, "shout", 3, "Quack!");
Update: How to use the later function through chaining in jQuery? Read my post.