为什么在JavaScript中(super .__ proto__ === this .__ proto__)是正确的?

Jen*_*ser 10 javascript ecmascript-6

似乎在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();
Run Code Online (Sandbox Code Playgroud)

我本来希望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__此示例中的原因?如果可能的话,还请提供对规范相关部分的引用。

Ry-*_*Ry- 6

Object.prototype.__proto__是具有吸气剂的属性[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__'));
Run Code Online (Sandbox Code Playgroud)