似乎在JavaScript(ES6)类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()
的函数Level1
和那个super.__proto__ !== this.__proto__
。相反,super.__proto__.myFunc();
实际上会调用类myFunc()
的{{1}}(它会自我调用),然后在第二次调用时会调用类Level3
的{{1}}。如果代码演示了myFunc()
,这是完全可以理解的。
您能否解释一下此示例中Level2
的原因?如有可能,还请提供对规范相关部分的引用。
答案 0 :(得分:6)
Object.prototype.__proto__
是具有吸气剂的属性 [1] 。它以其this
值运行。没有实际的super
对象是this
的值(您不能写Object.getPrototypeOf(super)
),而只是一种super
查找属性的方式,因此{{1} }和this.__proto__
的意思是相同的,只要super.__proto__
也没有在原型链的较低位置定义。
比较:
__proto__