箭头函数和原型继承范围问题

时间:2019-08-12 18:47:51

标签: javascript

我编写了4种输出Game.name的方法。为什么#3用${this.name}输出“未定义”,但是当我将其更改为${myGame.name}时却得到正确的标题?

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

我是JavaScript的新手,但是有Python经验,这在直觉上对我来说很奇怪。 #3和#4也是实现getName()的最佳实践吗?

0 个答案:

没有答案