Ben*_*son 2 javascript instance-variables es6-class
尝试运行时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');
Run Code Online (Sandbox Code Playgroud)
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}`);
};
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
40 次 |
| 最近记录: |