Call and apply

Call and apply methods are very frequently used methods in JavaScript and both function allow us in setting this value explicitly, borrowing functions from other object.

The only difference between Call and apply is the way we pass parameters to them.

In call method we pass arguments individually (i.e. named set of parameters) whether in apply we pass arguments as an array which is more useful in case of executing variable-arity functions.

variable-arity functions are known as variadic functions. These functions accept any number of arguments.

The Math.max() is a common example of variable-arity function.

We can pass any number of arguments to this function.

Console.log(Math.max(78,29,22,89,98));//98

Or you can pass array of numbers instead of passing N number of arguments.

var argArray = [78,29,22,89,98];

Console.log(Math.max(argArray));//98

Note: Wherever call method is used in example apply method can also be applied there. As you know the only difference between call and apply is the way we pass parameters.

Setting this value

 Let's understand this by simple example. 

 
var roots=0;

function getSquareRoots(numbers){
	this.roots = numbers.map(Math.sqrt);
}

var data = {
	numbers: [4, 9, 16],
	roots:0
}

// Simple call will set roots value to global 
// 'roots' variable (i.e. in roots variable in window scope)
getSquareRoots(data.numbers);
console.log(data.roots); // 0

console.log(window.roots); //[2,3,4]

// so to set roots value of data object we can use call or apply method.

getSquareRoots.call(data, data.numbers);
console.log(data.roots); //[2,3,4]
// Similarly you can use apply method as well. 
// The only difference is I am passing the parameter as an array.
getSquareRoots.apply(data, [data.numbers]);
console.log(data.roots); //[2,3,4]

 

Used for Chaining Constructor

Call and apply method used for chaining constructor, which is useful for implementing prototypical Inheritance in JavaScript. To see how to implement Inheritace in JavaScript refer OOP's in JavaScript.

Let's see the example

 

 function Shape(name, color) {
    this.name = name;
    this.color = color;

    return this;
}
Shape.prototype.displayShape = function (){
    console.log("Name : "+this.name+" color: "+this.color);
}
function Rectangle(name, color) {
// Here we are using call method for chaining constructor
    Shape.call(this, name, color); 
// Added extra property to different shapes.
    this.sides = '4';
}
// Create a Rectangle.prototype object that inherits from Shape.prototype.
// Note: A common error here is to use "new Shape()" to create the
// Rectangle.prototype. The correct place to call Shape is above, 
// where we call t from Rectangle. 
// Similarly other shapes object created and Inherited from Shape class.
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle; // Reset the constructor from Shape to Rectangle
Rectangle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
function Triangle(name, color) {
// you can use apply for chaining the constructor.
    Shape.call(this, name, color);
    this.sides = '3';
}
Triangle.prototype = Object.create(Shape.prototype);
Triangle.prototype.constructor = Triangle; // Reset the constructor from Shape to Triangle
Triangle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
function Circle(name, color) {
    // you can use apply also for chaining the constructor. 
    // The only difference is the way we pass parameter.
    Shape.call(this, name, color);
    this.sides = '0';
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle; // Reset the constructor from Shape to Circle

Circle.prototype.changeColor = function (colr){
    this.color = colr;
    console.log("Color Changed for "+this.name);
}
var rect = new Rectangle('Rectangle', 'red');
var tri = new Triangle('Triangle', 'Blue');
var cir = new Circle('Circle', 'Green');

rect.displayShape(); //Name : Rectangle color: red
tri.displayShape(); // Name : Triangle color: Blue
cir.displayShape();// Name : Circle color: Green
rect.changeColor("blue") //Color Changed for Rectangle
rect.displayShape(); //Name : Rectangle color: blue
tri.changeColor("Green") //Color Changed for Triangle
tri.displayShape(); //Name : Triangle color: Green
cir.changeColor("Red") //Color Changed for Circle
cir.displayShape(); //Name : Circle color: Red
 

 

In the above example apply method set this value to callbackObj. Which allow us to execute the callback function with this value set explicitly and the parameter passed to the callback function will be set on 'formatName' object.

 

Call and apply method can be used for calling anonymous functions.

 

Use for Borrowing functions

call and apply method used for borrowing functionalities from other objects. For example we can borrow Array's useful functionality in array-like object. For example you can use push, pop and other methods of an Array object.

 

An array-like object is an object that has its key defined as non-negative integers.

 Let's understand this by example also add a 'length' property in array-like object, so that we can relate an array-like object to an array object.

 

 
var arrayLikeObj = {0:"Deepak", 1:"Singh", 2:"35", length:3};
var newArray = Array.prototype.slice.call(arrayLikeObj, 0);
console.log(newArray);
// You can use push method.
Array.prototype.push.call(arrayLikeObj, 'Cincinnati');
// You can notice here the length of the object got changed.
console.log(arrayLikeObj); //{0:"Deepak", 1:"Singh", 2:"35", 3:"Cincinnati" length:4}
// You can do search as well.
var index = Array.prototype.indexOf.call(arrayLikeObj, 'Cincinnati');
console.log(index); // 3
// You can use pop, reverse and other methods to get the benefits 
// of Array functions in an array-like objects.

 

More frequent use of call and apply methods are for extracting the parameter passed to JavaScript functions from an arguments object which is property of all JavaScript functions and is an array-like object.

 For Example: 

function list(){
    console.log(arguments);
    return Array.prototype.slice.call(arguments, 0);
}
console.log(list(1,2,3,4,5)); //[1, 2, 3, 4, 5]
console.log(list("UP", "MH", "BH", "HY")); // ["UP", "MH", "BH", "HY"]

 

Hope you have got fare understanding of call and apply method in JavaScript.

Keep Reading and Keep Learning.

References:

MSDN call() function

MSDN apply() function

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/