[英]Why is my instance property undefined when used in a class method?
尝试运行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');
type
和其他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}`);
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.