[英]Why is my instance property undefined when used in a class method?
When trying to run cow1.voice();
尝试运行
cow1.voice();
and I keep getting an error in the console. 而且我在控制台中不断出现错误。
Uncaught ReferenceError: type is not defined
未捕获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
and others are instance variables of your class, so you need to use this
to access them. type
和其他type
是类的实例变量,因此您需要使用this
来访问它们。 The initial variables name
, type
, color
, provided to the constructor are used for class initialisation and aren't available outside of constructor. 提供给构造函数的初始变量
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.