Thursday, April 18, 2013

.call and .apply in JavaScript!

.call was explained to me in an interview today:

function whatever() {
   alert(this);
}
$(function () {
   whatever.call("Hello World");
});

 
 

Here is it is in a different shape of sorts:

function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
$(function () {
   whatever.call(undefined, "Sally", "blueberries");
});

 
 

This (no pun intended) shows off the difference between .call implementation immediately above and the .apply implementation here:

function whatever(name, taste) {
   alert(name + " likes " + taste + ".");
}
$(function () {
   whatever.apply(undefined, ["Roy", "strawberries"]);
});

No comments:

Post a Comment