0

I ran below code from javascriptissexy

Changed apply to bind. bind did not generate output but apply does

var person = {
   firstName   :"Penelope",
   lastName    :"Barrymore",
   showFullName:function () {
// The "context"
console.log (this.firstName + " " + this.lastName);
 }
}

/* The "context", when invoking showFullName, is the person object, 
   when we invoke the showFullName () method on the person object.*/

/* And the use of "this" inside the showFullName() method has the value of 
   the person object */

person.showFullName (); // Penelope Barrymore

// If we invoke showFullName with a different object:
var anotherPerson = {
firstName   :"Rohit",
lastName    :"Khan"
};

// We can use the apply method to set the "this" value explicitly—more on the apply () method later.
// "this" gets the value of whichever object invokes the "this" Function, hence:

person.showFullName.bind (anotherPerson); // No output

person.showFullName.apply (anotherPerson); // Rohit Khan

What is the reason for bind did not generate any output?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211

1 Answers1

3

bind - return function.

apply - call function.

That's why you get different results.


Just call function that return bind

var person = {
  firstName: "Penelope",
  lastName: "Barrymore",
  showFullName: function() {
    // The "context"
    console.log(this.firstName + " " + this.lastName);
  }
}

/* The "context", when invoking showFullName, is the person object, 
   when we invoke the showFullName () method on the person object.*/

/* And the use of "this" inside the showFullName() method has the value of 
   the person object */

person.showFullName(); // Penelope Barrymore

// If we invoke showFullName with a different object:
var anotherPerson = {
  firstName: "Rohit",
  lastName: "Khan"
};

// We can use the apply method to set the "this" value explicitly—more on the apply () method later.
// "this" gets the value of whichever object invokes the "this" Function, hence:

person.showFullName.bind(anotherPerson)(); // No output
// ------------------------------------^^

person.showFullName.apply(anotherPerson); // Rohit Khan
Grundy
  • 13,356
  • 3
  • 35
  • 55