in javascript call bind apply programming ~ read.

call(), apply(), and bind()

This is certainly one of the favourite questions in JS interviews. The simplest way to remember what these methods do is to control what this keyword points to. All function in JS have access to call(), bind(), and apply() method.

For e.g.

var person = {  
  firstName: 'Jon',
  lastName: 'Doe',
  getFullName: function() {
    var fullName = this.firstName + ' ' + this.lastName;
    return fullName;
  }
}

var logName = function(lang1, lang2) {  
  console.log('Logged: ' + this.getFullName());
}

Now if I am doing logName() it will raise an exception because this keyword does have the function getFullName defined on it. What we can do is we can pass the person object to the bind method of logName function, and then this keyword will point to the person object which has the getFullName method defined, so there are two ways of doing this

var logPersonName = logName.bind(person);  
logPersonName();  
//another method
var logName = function(lang1, lang2) {  
  console.log('Logged: ' + this.getFullName());
}.bind(person);
logName();  

Also another thing to be noted here is that bind will create a new function, so for this example it will create a copy of logName function, and with bind we can call the method later on which is the difference between bind, and call and apply. call and apply will invoke the function.

The difference between call() and apply() is the way we pass arguments to the function, with call we have to pass the argument one by one and with apply we can pass the arguments as a list.

logName.call(person, 'en', 'es');  
logName.apply(person, ['en', 'es']);