我已经看到'self'变量可以使用'function'类声明在javascript类中设置为更可预测的'this'用法。我们如何使用“ class”声明来做到这一点?
// Using the 'function' declaration
function Apple (type) {
var self = this
self.type = type
self.color = "red"
self.getInfo = function() {
return self.color + ' ' + self.type + ' apple'
};
}
// Using the 'class' declaration
class Apple2 {
constructor(type){
var self = this
self.type = type
self.color = "red"
}
getInfo () {
return self.color + ' ' + self.type + ' apple'
}
}
let ap = new Apple('Granny')
let ap2 = new Apple2('Jazz')
console.log(ap.getInfo(), ap2.getInfo())
// prints 'red Granny apple undefined undefined apple'
看起来好像在chrome控制台中的构造函数实际工作之前创建了'self'变量,但是webpack为此抛出了错误:
// Using the 'class' declaration
class Apple2 {
self = this
constructor(type){
self.type = type
self.color = "red"
}
getInfo () {
return self.color + ' ' + self.type + ' apple'
}
}
console.log(new Apple2('Jazz').getInfo())
答案 0 :(得分:1)
使用类的正确方法是不别名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))
有关此行为的更多信息,请参见How does the "this" keyword work?