Eggs
Eggs

Reputation: 345

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(); 

Upvotes: 1

Views: 617

Answers (2)

Julien Ambos
Julien Ambos

Reputation: 2088

  1. In an object literal you can not reference to the variable name that the object will be assigned to.
  2. Person1.getName : Person.getFullName.bind(Person1) is not the correct syntax to declare a method in an object literal. You are doing it correctly in var Person.

Your code has to be:

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

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222369

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
}

Upvotes: 1

Related Questions