Call and Apply

Modifying the 'this'

Example 1:

var person = {
  firstName: "Nelson", 
  printName: function() {
      console.log(this.firstName); //we don't know what 'this' is pointing to
  }
}

var test = person.printName; //We are extracting the printName from person, therefore we lose the context (person) 
test(); -> Result in 'undefined' 

//What is wanted to alias the printName function out and apply it against any arbitrary objects. 
//Eg, what if wanted to access the printName in person2: 
var person2 = {
  firstName: "Foo"
}

//We want to call test function on person2; 
//We can't do person2.test -> Results in TypeError 
//We could steal it like: 

var person2 = {
  firstName: "Foo"
  test: person.printName
}

//A better way would be using call or apply: 

//We can do:
test.call(person2); //We just override the 'this' value. What this means is, call the test function, but use person2 object as 'this.

//We could also have done:
person.printName.call(person2);

Call vs Apply

Both do the same thing but:

  • Call accepts it as a variable list of parameters
  • Apply uses a an array of argument
var person = {
  firstName: "Nelson", 
  printName: function(prefix) {
      console.log(prefix + " " + this.firstName);
  }
}

var person2 = {
  firstName: "Foo"
}

var myLocalPrintName = person.printName;
myLocalPrintName.call(person2, "Mr"); 
myLocalPrintName.apply(person2, ["Mr"]);

results matching ""

    No results matching ""