For a long time javascript call
and apply
have been really confusing me. I neither know when to use it nor what are the differences between these two.
Basically call
and apply
invoke the function and switch the function context with the first argument. The main difference between these two is with call
the rest arguments are passed to the calling function and those arguments have to be listed explicitly. However with apply
the amount of arguments don’t have to be predefined. we can pass in an array.
function fn( arg1, arg2,... ){ // do something } fn( arg1, arg2,... ); fn.call( context, arg1, arg2,... ); fn.apply( context, [ arg1, arg2,... ]);
It’s not necessary to have the second argument
A real world use case
Ajax is a good example to use call
and apply
.
function Album( id, title, owner_id ){ this.id = id; this.name = title; this.owner_id = owner_id; }; Album.prototype.get_owner = function( callback ){ var self = this; $.get( '/owners/' + this.owner_id , function( data ){ callback && callback.call( self, data.name ); }); }; var album = new Album( 1, 'node.js conf', 2 ); album.get_owner( function( owner ){ alert( 'The album' + this.name + ' belongs to ' + owner ); });
Speed
Function invoke with call
is slightly faster than with apply
. But don’t worry, you really can’t tell the difference, use whatever suits you.