尝试运行cow1.voice();
时,控制台中始终出现错误。
未捕获的ReferenceError:类型未定义
class Cow {
constructor(name, type, color) {
this.name = name;
this.type = type;
this.color = color;
};
voice() {
console.log(`Moooo ${name} Moooo ${type} Moooooo ${color}`);
};
};
const cow1 = new Cow('ben', 'chicken', 'red');
答案 0 :(得分:6)
type
和其他变量是您的类的实例变量,因此您需要使用this
来访问它们。提供给构造函数的初始变量name
,type
,color
用于类初始化,在构造函数之外不可用。
class Cow {
constructor(name, type, color) {
this.name = name;
this.type = type;
this.color = color;
};
voice() {
// Access instance vars via this
console.log(`Moooo ${this.name} Moooo ${this.type} Moooooo ${this.color}`);
};
};