[英]Accessing a class field on a superclass
我有一個包含以下代碼的文件:
class Animal { doSomething = () => { return 'Hi.'; }; } class Dog extends Animal { doSomething = () => { return super.doSomething() + ' Woof!'; }; } console.log(new Dog().doSomething());
注意:嘗試運行上面的代碼段可能不起作用,因為我不知道如何使用我的 Babal 設置。
無論如何,當我使用 Babel 編譯它並在 Node 中運行它時,我收到以下錯誤:
/Users/elias/src/classFieldTest/build/classFieldTest.js:15
return super.doSomething() + ' Woof!';
^
TypeError: (intermediate value).doSomething is not a function
at Dog.doSomething (/Users/elias/src/classFieldTest/build/classFieldTest.js:15:26)
at Object.<anonymous> (/Users/elias/src/classFieldTest/build/classFieldTest.js:21:23)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
我使用 Babel 6.26.0 和stage-2
預設,以及 Node 8.11.1。 如果有人關心,我可以顯示我正在使用的命令。
為什么會這樣? 我猜super
不能用於訪問類字段,但是我該怎么辦呢? 如果我將Animal
的doSomething
方法更改為傳統方法( doSomething() { return 'Hi.'; }
),它會起作用,但我寧願避免傳統方法,因為它們重新定義了this
以及它引起的所有混亂。
有沒有辦法訪問超類的類字段?
為什么會這樣? 我猜 super 不能用於訪問類字段
是的。 類字段是實例屬性,但super
嘗試訪問超類的原型對象上的屬性。 您的Animal
類根本沒有doSomething
方法 - 相反,每個Animal
對象都有一個包含綁定函數的屬性。
但我該怎么辦呢? 如果我將其更改為傳統方法,它會起作用
是的,你應該這樣做。 這就是方法和super
工作方式。
當您不需要箭頭函數時,尤其是當它們不起作用時,請避免使用它們。 另請查看類屬性中的箭頭函數可能沒有我們想象的那么好。
有沒有辦法訪問超類的類字段?
是的 - 它是一個實例屬性,您可以在覆蓋它之前在構造函數中訪問它:
class Animal {
constructor() {
this.doSomething = () => {
return 'Hi.';
};
}
}
class Dog extends Animal {
constructor() {
super();
const superDoSomething = this.doSomething;
this.doSomething = () => {
return superDoSomething() + ' Woof!';
};
}
}
或者,使用類字段提議並且沒有顯式構造函數:
class Animal {
doSomething = () => {
return 'Hi.';
}
}
class Dog extends Animal {
doSomething = (superDoSomething => () => {
return superDoSomething() + ' Woof!';
})(this.doSomething)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.