Wednesday, March 11, 2009

Function.apply, Function.call and Argument list in JavaScript

I have just read about the function.apply and function.call in Scott Allen's post. It's a very useful post talking about the details of how to use it.

Do you know what the following code means?

function sample(message) {
alert(this.toString());
alert(arguments.length);
alert(arguments[0] + arguments[1]);
}

function sample2(object, func, args){
func.apply(object, args);
}

function sample3(message1, message2){
alert(this.toString() + message1 + message2);
}
var text = "Do you understand the code?";
sample.call(text, "Text 1", " and some more text");
alert("Running Sample 2");
sample2(text,sample3,[" Yes", ", I do"]);


Just read and learn:
http://odetocode.com/blogs/scott/archive/2007/07/04/11067.aspx

No comments: