gpt4 book ai didi

javascript - 访问由 Object.create 创建的对象中的父( super )方法

转载 作者:行者123 更新时间:2023-12-03 01:00:50 25 4
gpt4 key购买 nike

我想创建一个包装器机制:我们包装 c 所以新的新对象 w 拥有自己的属性和方法,但 c 是也可以访问。

// Note: this class might be from an external lib
class C {
f() {
console.log('f (original)');
this.p = 'p';
}
}

class W {
f() {
console.log('f (new)');
super.f(); // TypeError: (intermediate value).f is not a function
console.log(this.p);
}
}

// Note: this value is external for us
const c = new C();

const w = Object.create(null, Object.getOwnPropertyDescriptors(W.prototype));
Object.setPrototypeOf(w, c);

w.f(); // expected:
// f (new)
// f (original)
// p

我这样做的方式正确吗?

为什么会出现错误?

更新:我确实知道我可以使用组合,但我想了解错误的根源。

最佳答案

Why does the error happen?

因为使用superW.prototype.f方法只关心W.prototype的原型(prototype)来评估什么 super 将引用。 super 关键字本质上是静态查找,具体取决于声明该方法的对象,忽略调用该方法的对象的原型(prototype)链。

如果我们translate

class W {
f() {
console.log('f (new)');
Object.getPrototypeOf(W.prototype).f.call(this); // TypeError: (intermediate value).f is not a function
console.log(this.p);
}
}

我们可以看到Object.prototype.f不是一个函数......

<小时/>

因此,您可以通过执行 Object.setPrototypeOf(W.prototype, C.prototype) 而不是 Object.setPrototypeOf(w, c) (或 w = Object.create(c, …)),但我不建议这样做。如果您确实想影响所有实例,那么您已经编写了 class W extends C (这与使用 Object.setPrototypeOf(W.prototype, C.prototype) 的结果相同) )。

关于javascript - 访问由 Object.create 创建的对象中的父( super )方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52628804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com