亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何擴展從 ES6 中的父類繼承的類屬性?

如何擴展從 ES6 中的父類繼承的類屬性?

繁星coding 2021-11-12 16:46:40
我有以下代碼:class Parent {    some_class_property = [1,2,3];    some_other_methods(){...}}class Child extends Parent {    some_class_property = super.some_class_property.push(4);}控制臺給我一個語法錯誤,說關鍵字super是意外的。如果 ES6 中允許類屬性,那么不允許它在子類中擴展又有什么意義呢?如果這不是正確的方法,那么該怎么做?謝謝。
查看完整描述

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();



查看完整回答
反對 回復 2021-11-12
?
飲歌長嘯

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(){...}

}


查看完整回答
反對 回復 2021-11-12
  • 2 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號