2 回答

TA貢獻1831條經驗 獲得超9個贊
看起來super類字段中不允許引用,這就是您當前代碼拋出錯誤的原因。
但是,在超類構造函數中將some_class_property放在實例化對象本身上(好吧,在類字段中,這是將它放在超類構造函數中的對象上的有效語法糖),這意味著您可以在子類中引用它參考this.some_class_property. 您沒有引用隱藏的方法或屬性,因此super不需要:
class Parent {
some_class_property = [1, 2, 3];
}
class Child extends Parent {
some_class_property = this.some_class_property.push(4)
}
const c = new Child();
console.log(c.some_class_property);
還要記住,.push返回數組的新長度,這就是為什么上面代碼片段的結果是4. (如果您想復制some_class_property數組,無論出于何種原因,請改用some_class_property = [...this.some_class_property, 4])
使用的時間super是當子實例或子原型上存在屬性,但您想引用父原型上的屬性時,例如:
class Parent {
method() {
console.log('parent method');
}
}
class Child extends Parent {
method() {
console.log('child method');
}
invokeParentMethod() {
super.method();
}
}
const c = new Child();
c.method();
c.invokeParentMethod();

TA貢獻1951條經驗 獲得超3個贊
公共和私有屬性是處于實驗階段(ES11?)的 Javascript 特性。在 ES6 的過去幾年中,人們一直在這樣做:
class Parent {
constructor(x){
this.property1 = [1,2,3];
...
}
some_other_methods(){...}
}
Parent.property2 = [4,5,6]; // to access: Parent.property1
Parent.prototype.property3 = [7,8,9]; // to access: obj.property2
class Child extends Parent {
constructor(x){
super(x);
// ...
}
some_other_methods(){...}
}
添加回答
舉報