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