Friday, December 19, 2014

call() and apply() method in JavaScript

call() and apply() method - Explicit binding

The call() method calls a function with a given "this" value and arguments provided individually.
                         
                         fun.call(thisValue, arg1, arg2, - - - -);

The apply() method calls a function with a given this value and arguments provided as an array.

                         fun.call(thisValue, [argArray]);

call and apply method tells that on whose context you want to execute the function.

var person = {
init : function(name) {
this.name = name;
},
getName : function() {
console.log(this.name);
}
};
person.init("Deepak");
person.getName(); // "Deepak"
// Here getName method is invoked in the context of person object
var anotherPerson = {
name : "Chetan"
};
person.getName.call(anotherPerson); // "Chetan"
//person.getName.apply(anotherPerson); // "Chetan"
// Here getName method is invoked in the context of anotherPerson
view raw gistfile1.js hosted with ❤ by GitHub

person.getName.call(anotherPerson) here value of "this" inside getName() method is anotherPerson.

Arguments object do not have Array's methods but we can invoke Array's method explicitly by using call() and apply().

function myFunction() {
Array.prototype.push.call(arguments, "four");
//Array.prototype.push.apply(arguments, ["four"]);
console.log(arguments[3]); // "four"
}
myFunction("one", "two", "three");
view raw gistfile1.js hosted with ❤ by GitHub

above two program can be done either using call() or apply() method

Where to use call() and where to use apply() method

When we don't know about number of arguments then we should use apply() method otherwise we can use call() method.

var person = {
init : function(id , name) {
this.id = id;
this.name = name;
},
getName : function() {
console.log(this.name);
}
};
person.init(111, "Deepak");
person.getName(); // "Deepak"
function getObject(obj) {
var extendObj = Object.create(obj);
var argu = [];
for(var i=1; i < arguments.length; i=i+1) {
argu.push(arguments[i]);
}
obj.init.apply(extendObj,argu);
return extendObj;
}
var p1 = getObject(person , 121 , "Chetan");
//var p1 = Object.create(person);
//p1.init(121 , "Chetan");
p1.getName(); // "Chetan"
view raw gistfile1.js hosted with ❤ by GitHub

Link 1 - Explicit binding
Link 2 - Explicit binding
Link 3 - Explicit binding

No comments:

Post a Comment