Правильный способ для классов: , а не псевдоним this
:
class Apple2 {
constructor(type) {
this.type = type
this.color = 'red'
}
getInfo() {
return `${this.color} ${this.type} apple`
}
}
console.log(new Apple2('Jazz').getInfo())
Причина в том, что это фактически (приблизительно) эквивалентно следующему коду:
function Apple(type) {
this.type = type
this.color = 'red'
}
Apple.prototype.getInfo = function() {
return this.color + ' ' + this.type + ' apple'
}
console.log(new Apple('Granny').getInfo())
, поэтому использование this
работает.На самом деле, даже с вашим исходным кодом, псевдоним не был необходим:
function Apple(type) {
this.type = type
this.color = 'red'
this.getInfo = function() {
return this.color + ' ' + this.type + ' apple'
}
}
var apple = new Apple('Granny')
// does not make a difference
console.log(apple.getInfo())
var getInfo = apple.getInfo
// here is where it makes a difference
console.log(getInfo())
// how to fix
console.log(getInfo.call(apple))
Подробнее об этом поведении см. Как работает ключевое слово "this"?