Bind, Call, Apply - Javascript Function

Javascript examples for Function:Function Call

Description

Bind, Call, Apply

Demo Code


var john = {/*from   w ww.  j a  va  2  s. co  m*/
  name: "John",
  age: 26,
  job: "teacher",
  presentation: function(style, timeOfDay) {
    if (style === "formal") {
      console.log("Good " + timeOfDay + ", ladies and gentlemen. I\'m " + this.name + ", and I\'m a " + this.job + " and I\'m " + this.age + " years old.");
    }
    else if (style === "friendly") {
      console.log("Hey, what\'s up? I\'m " + this.name + ". I\'m a " + this.age + "-year-old " + this.job + ". Have a good " + timeOfDay + ".");
    }
  }
};

john.presentation("formal", "morning");
john.presentation("friendly", "afternoon");

// Call:

var emily = {
  name: "Emily",
  age: 35,
  job: "designer"
}

// Set "this" parameter to the emily object instead of john using the CALL method:
john.presentation.call(emily, "friendly", "afternoon");
john.presentation.call(emily, "formal", "morning");

// Apply:
// Same thing, but using the APPLY method, which takes an array instead:
john.presentation.apply(emily, ["friendly", "afternoon"]);

// Bind:

var johnFriendly = john.presentation.bind(john, "friendly");
// Now you only need the last argument.
johnFriendly("morning");
johnFriendly("night");

var emilyFormal = john.presentation.bind(emily, "formal");
// And again, you only need to pass in the last argument:
emilyFormal("evening");

Related Tutorials