What is the difference between .call() and .apply()?

Answer

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
varsomeObject={
 
myProperty:'Foo',
 
myMethod:function(prefix,postfix){
 
alert(prefix+this.myProperty+postfix);
 
}
 
};
 
someObject.myMethod('<','>');// alerts '<Foo>'
 
varsomeOtherObject ={
 
myProperty:'Bar'
 
};
 
someObject.myMethod.call(someOtherObject,'<','>');// alerts '<Bar>'
 
someObject.myMethod.apply(someOtherObject,['<','>']);// alerts '<Bar>'

All javascript Questions

Ask your interview questions on javascript

Write Your comment or Questions if you want the answers on javascript from javascript Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---