Categories
interview

Javascript call() vs apply() vs bind()

call

The call() is a predefined Javascript function which can used to call a method of an object while passing it another object. For example, if you look at the following code, you will observe that the object being passed into the call() method replaces the this variable of the object whose method is being invoked.

var mainObj = {
  person: 'John',
  age: 25,
  print: function() {
    console.log('Name: ' + this.person + ' Age: ' + this.age);
  }
}

var obj = {
  person: 'Smith',
  age: 26
};

mainObj.print(obj);
mainObj.print.call(obj);

Output

Name: John Age: 25
Name: Smith Age: 26

Demo

apply

The apply() is a predefined Javascript function similar to the call() function, the difference being that we can also pass arguments as arrays. For example.

var mainObj = {
  person: 'John',
  print: function(val1, val2, val3) {
    console.log(val1, val2, val3);
    console.log(this.person);
  }
}

var arr = [1, 2, 3];

mainObj.print.apply(mainObj, arr);

console.log(Math.max.apply(null, arr));
console.log(Math.min.apply(null, arr));

Output

1 2 3
John
3
1

Demo

Note
In non-strict mode, when null is the first argument for apply(), then the default global value will be used for this. Otherwise the first argument passed in apply() is used for the value of this.

bind

The bind() function is a predefined Javascript function too. It is used to create a new function, that can be bound by what ever object you pass it with. For example.

var mainObj = {
  person: 'John',
  print: function() {
    console.log(this.person);
  }
}

var obj = {
  person: 'Smith'
};


var nonWorkingPrint = mainObj.print;
// This won't work as this method doesn't have access to the 'mainObj' property 'person'.
nonWorkingPrint();

var print = mainObj.print.bind(obj);
print();

Output

undefined
Smith

Demo