0

I'm trying to return the name of the element inside of the object. Second element is function getBook() that should return the name of the book but I'm getting undefined in my console. I have defined the second variable get name that is referencing to the function inside of the object. I'm not sure if I can use return this.element. If anyone can explain why my code is failing I would appreciate that. Thank you.

var books = { 
    name: 'Goodnight Moon', 
    getBook() { 
        return this.name; 
    } 
}; 

var getName = books.getBook; 
console.log(getName());
espresso_coffee
  • 5,980
  • 11
  • 83
  • 193

2 Answers2

2

You need to bind() books to the getName function expression. Otherwise the context of this will refer to the window object:

var books = {
  name: 'Goodnight Moon',
  getBook() {
    return this.name;
  }
};

var getName = books.getBook.bind(books);
console.log(getName());
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • Carl, thanks for taking time to respond. Please would you explain why we have to use bind and why my original code for returning undefined? – espresso_coffee Dec 18 '17 at 23:13
  • 1
    I updated my answer. Let me know if it needs further explanation. – Carl Edwards Dec 18 '17 at 23:14
  • @espresso_coffee: Think of `this` as another function parameter. It gets set by the caller to some value depending on how the function was invoked. You can also set it manually when invoking like `getName.call(books)`, or as shown above, you can create a new function using `.bind()` that has a value permanently bound as the value of `this`. –  Dec 18 '17 at 23:17
0

Of course you could simply do

// same object definition
var books = { 
    name: 'Goodnight Moon', 
    getBook() { 
        return this.name; 
    } 
};

// but call:
books.getBook();
console.log(books.getBook());
Sébastien
  • 11,860
  • 11
  • 58
  • 78