似乎在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()class Level1和that 的功能super.__proto__ !== this.__proto__。相反,super.__proto__.myFunc();实际上是调用myFunc()class Level3(它自己调用),然后在第二次调用时调用myFunc()class Level2。如果super.__proto__ === this.__proto__代码演示的话,这是完全可以理解的。
您能否解释super.__proto__ === this.__proto__此示例中的原因?如果可能的话,还请提供对规范相关部分的引用。
__proto__实际使用访问器函数Object.prototype并按其this值进行操作有关。但是我只是无法想象super实际上是指定以这种方式工作的。我以为super大致等同于this.__proto__.__proto__,因此super.__proto__应该等同于this.__proto__.__proto__.__proto__表现出我期望的行为。您知道规范中在哪里super指定了确切的行为吗?