The difference between apply and call method in javascript
by toy
Well, I have just an issue from my friend who have a problem with arguments passed in the extended method. This topic I will show the difference between apply and call method.
First, what is call and apply method. This is a hard question for me to explain this kind of question in English. Haha. But I will try. Instead of explain myself I decided to lift somebody’s context up from This
apply
Syntax
functionreference.apply(thisArg, argArray)
Parameters
thisArg (parameter for the calling object)
argArray (an optional parameter of an argument array for the object)
Description
apply allows you to apply a method of another object in the context of a different object (the calling object). You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With apply, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
call
Syntax
functionreference.call(thisArg, arg1, arg2, …)
Parameters
thisArg (parameter for the calling object)
arg1, arg2, … (an optional parameters of arguments for the object)
Description
call allows you to call (executes) a method of another object in the context of a different object (the calling object). You can assign a different this object when calling an existing function. this refers to the current object, the calling object. With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
This is an example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 function Person(name)
{
var total = 0;
for ( var i=0; i<arguments.length; i++ )
{
total += arguments[i];
}
console.log( "length of arguments", arguments.length );
console.log( "arg0" , arguments[0] );
console.log( "arg1" , arguments[1] );
this.name = name;
}
Person.prototype.getName = function()
{
return this.name;
}
// class User (will be subclassing Person)
function User(name, pwd)
{
// Constructor Chaining (calling superclass constructor)
Person.apply(this, arguments);
Person.call(this,name,pwd);
this.pwd = pwd;
}
var user = new User( "Toy", "Toy1" );
Twitter
Facebook