[英]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.