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

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

為什么在 JavaScript 中是真的?

為什么在 JavaScript 中是真的?

一只甜甜圈 2021-11-18 15:42:37
似乎在 JavaScript (ES6) Classes 中super.__proto__ === this.__proto__。你能解釋為什么會這樣嗎?這種行為在不同的瀏覽器中似乎是一致的,所以我懷疑這是在規范中的某處指定的。考慮以下代碼:class Level1 {    myFunc() {        console.log('Level1');    }}class Level2 extends Level1 {    myFunc() {        console.log('Level2');    }}class Level3 extends Level2 {    myFunc() {        console.log('Level3 BEGIN ' + Math.random());         super.__proto__.myFunc();        console.log(super.__proto__ === this.__proto__);        console.log('Level3 END');     }}const foo = new Level3();foo.myFunc();我原以為super.__proto__.myFunc();會調用myFunc()class的函數,Level1而super.__proto__ !== this.__proto__. 相反,super.__proto__.myFunc();實際上調用myFunc()class Level3(它調用自己),然后在第二次調用時調用myFunc()class Level2。如果super.__proto__ === this.__proto__代碼演示了這一點,這是完全可以理解的。你能解釋一下super.__proto__ === this.__proto__這個例子中的原因嗎?如果可能,還請提供對規范相關部分的參考。
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

Object.prototype.__proto__是一個帶有 getter [1]的屬性。它以其this價值運作。沒有實際的super對象是一個this值(你不能寫Object.getPrototypeOf(super)),只是一種super查找屬性的方式,所以只要沒有在原型鏈的較低位置定義,this.__proto__并且super.__proto__意味著相同的東西__proto__。


相比:


class Parent {

    get notProto() {

        return this instanceof Child;

    }

}


class Child extends Parent {

    test() {

        console.log(super.notProto);

    }

}


new Child().test();


// bonus: [1]

console.log(Object.getOwnPropertyDescriptor(Object.prototype, '__proto__'));


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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