似乎在 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()
类Level3
(它调用自身),然后在第二次调用时调用 myFunc()
类Level2
。这是完全可以理解的,如果 super.__proto__ === this.__proto__
代码演示了这一点。
你能解释一下原因吗super.__proto__ === this.__proto__
在这个例子中?如果可能,还请提供规范相关部分的引用资料。
最佳答案
Object.prototype.__proto__
是一个带有 getter[1] 的属性。它对其 this
值进行操作。没有实际的 super
对象作为 this
值(您不能编写 Object.getPrototypeOf(super)
),只是一个 >super
查找属性的方式,因此只要 __proto__
不存在,this.__proto__
和 super.__proto__
就意味着相同的事情也没有在原型(prototype)链的任何较低位置进行定义。
比较:
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__'));
关于javascript - 为什么在 JavaScript 中 (super.__proto__ === this.__proto__) 为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58348760/