0

I've written 4 methods that outputs the Game.name. Why does #3 output "undefined" with ${this.name} but when I change it to ${myGame.name} I get the right title?

let Game = function(name, releaseDate) {
  this.name = name
  this.releaseDate = releaseDate
}

// #1 Instantiate Game object
let myGame = new Game('Legend of Zelda', 'Jan 1, 2001')
console.log(`Test #1. The game name is ${myGame.name}`) // Test #1. The game name is Legend of Zelda

// #2 Regular prototype method implementation
Game.prototype.getName = function() {
  console.log(`Test #2. The game name is ${this.name}`) // Test #2. The game name is Legend of Zelda
}
myGame.getName()

// #3 Prototype inheritance of a new getName() method
Game.prototype.getName2 = () => console.log(`Test #3. The game name is ${this.name}.`)
myGame.getName2() // Test #3. The game name is undefined.

// #4 Get the right title output.
Game.prototype.getName3 = () => console.log(`Test #4. The game name is ${myGame.name}`)
myGame.getName3() // Test #4. The game name is Legend of Zelda

I am new to JavaScript, but have experience in Python and this is just intuitively strange to me. Also are #3 and #4 the best practices to implement getName()?

adiga
  • 28,937
  • 7
  • 45
  • 66
Evan Kim
  • 639
  • 1
  • 4
  • 19
  • 2
    Arrow functions refer `this` in their lexical scopes :) – Shubh Aug 12 '19 at 18:49
  • 2
    In other words, arrow functions don't create their own scope context, so `this` still refers to the parent context. – silencedogood Aug 12 '19 at 18:50
  • I think lexical scope makes sense, but if I changed from `${this.name}` to `{Game.name}`, why does it output `Game` and not `undefined`? The parent context doesn't have any default parameters set so that's why I would expect an `undefined` – Evan Kim Aug 12 '19 at 18:54
  • `Game.name` gets the name of the `Game` function. And `${myGame.name}` would return `Legend of Zelda` with arrow functions and normal functions. In that case, the functions are taking closure over the `myGame` variable. – adiga Aug 12 '19 at 18:59
  • "*I am new to JavaScript, but have experience in Python*" - well, `this` in JavaScript works very different from `self` in Python, especially when using method references – Bergi Aug 12 '19 at 19:48

0 Answers0