我在 Javascript 中嘗試類和 this 關鍵字,我寫了這段代碼:
class p{
constructor(p,a){
p = p.p;
a = p.a;
};
};
const c = new p(p="1st aspect",a="2nd aspect");
console.log(this.c);
我得到了這個錯誤:
Cannot read properties of undefined (reading 'a')
我不知道這是否與類兼容,或者我是否傳入了錯誤的引數,有人可以幫我嗎?
uj5u.com熱心網友回復:
創建類的語法是錯誤的。您不需要傳遞引數名稱。只需使用
const c = new p("1st aspect","2nd aspect");
使用小寫的第一個字母作為類名也不是一個好習慣。使用P而不是p. 而且this.c是錯誤的。只需列印
console.log(c);
uj5u.com熱心網友回復:
就嘗試使用提供的引數名稱(“p =”,“a =”)而言,這只是您用于創建類實體的語法不正確,并且您的類構造中可能存在一些錯誤。我想你可能一直在嘗試做這樣的事情:
class p {
// These are ordered arguments, not named arguments
constructor(p,a) {
// Save the value of p and a on the class instance
this.p = p;
this.a = a;
};
};
// Create a new p class instance with the arguments in order
const classInstance = new p("1st aspect", "2nd aspect");
uj5u.com熱心網友回復:
代碼應如下所示
class P {
constructor(p, a){
this.p = p;
this.a = a;
};
};
const c = new P("1st aspect", "2nd aspect");
console.log(c); // <- just print c
我可以看到您混淆了一些概念并感到困惑,我建議您閱讀官方 MDN 檔案,您將逐步了解課程。
另外,您會注意到類名是使用PascalCase命名的。這是因為通過遵循命名約定,您將更快地閱讀和理解其他人的代碼(甚至是您的代碼)。
希望這有幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/471234.html
標籤:javascript 班级
