开发者

please explain the apply and call methods in javascript [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What is the difference between call and apply?

What is the main difference between apply and开发者_开发技巧 call methods... I go through the web but unable to find the best solution.. Please help me friends...


Every function in JavaScript receives two objects in addition to the default parameters. These are this and arguments. The value of this is determined by it's invocation pattern. apply or call can be used to invoke a function and provide it a default this object.

This will be very useful in many situations. For example, arguments is an array-like object, but not really an Array with all the useful Array methods. So, to apply an Array method slice on arguments, you can do this:

Array.prototype.slice.apply(arguments, [1, 2])

Had arguments been an object of Array type, you could have used

arguments.slice(1, 2) 

call is nothing but a modified version of apply. See elusive's comment.

Mr.Douglus Crockford gives a very good introduction to JavaScript functions in this video: Function the Ultimate.


The main difference is that call accepts a list of arguments, where arguments after the first one are passed directly to the method:

myFunc.call(thisObj, arg1, arg2, arg3);

Whereas apply accepts only two arguments - the first is the this object and the second is an array of arguments to pass to the method:

myFunc.apply(thisObj, [arg1, arg2, arg3]);

apply is often used in a situation where you want to pass the arguments object, which contains a list of arguments passed to the current function, to another method:

function myOtherFunc(arg1, arg2, arg3) {
    if (typeof arg1 == "object" && arg1 !== null)
        myFunc.apply(this, arguments);
}


.apply() and .call() are very similar. The only difference is how they pass arguments to the called function. .apply() takes an array of arguments, while .call() can be used like a regular function call:

someFunction.apply(context, [argument1, argument2]);

Is equivalent to:

someFunction.call(context, argument1, argument2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜