Search code examples
javascriptobjectbindingliteralsecmascript-5

Binding an object inside of an object literal's method (ES5)


I have two objects, Person and Person1, and I am trying to understand why I am unable to bind person1.getName to use a different methodName in the Person object. If I take the code below and run it in the console I get an output of

Name: undefined undefined

Here is my code:

var Person = {
  firstname : "John",
  lastName : "Doe",
  getFullName : function() {
    console.log("Name : " + this.firstname + " " + this.lastName);
  }
};

var Person1 = {
  firstname : "Jane",
  lastName : "Doe",
  Person1.getName : Person.getFullName.bind(Person1)  
}

Person1.getName(); 

However, if I remove the method from the Person1 object literal and add it after the fact the method works correctly in the code below:

var Person = {
  firstname : "John",
  lastName : "Doe",
  getFullName : function() {
    console.log("Name : " + this.firstname + " " + this.lastName);
  }
};

var Person1 = {
  firstname : "Jane",
  lastName : "Doe"
}

Person1.getName = Person.getFullName.bind(Person1);  
Person1.getName(); 

Solution

  • var Person1 is hoisted, and Person1 variable is defined but equal to undefined at the moment when Person.getFullName.bind(Person1) is evaluated.

    Due to how this works, the method doesn't require binding (unless it's used separately from its context, e.g. as callback).

    It should be:

    var Person1 = {
      firstname : "Jane",
      lastName : "Doe",
      getName : Person.getFullName
    }