gpt4 book ai didi

JavaScript 从非 ES6 类覆盖到 ES6 类

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:24 25 4
gpt4 key购买 nike

在我的 Webapp 中,我需要实现一个 API,它不包含任何 ES6 类定义,但我想扩展其中一个类并覆盖一些方法。覆盖无法正常工作...

function A() {
this.msg = function() {
console.log("A");
}
}

class B {
constructor() {
A.call(this);
}

msg() {
console.log("B");
}
}

new B().msg();

我希望结果是“B”,但是“类”A 的方法被执行了。

最佳答案

问题是在 A 中,msg 函数附加到构造函数中的 this - 那也就是说,msg 属性直接附加到实例对象本身,而不是原型(prototype)。相比之下,Bmsg 位于Bprototype 上——即B。 prototype,实例继承的对象。

一种选择是在 B 的构造函数中覆盖 msg:

function A() {
this.msg = function() {
console.log("A");
}
}

class B {
constructor() {
A.call(this);
this.msg = () => {
console.log('b');
}
}
}

new B().msg();

一个更好看的原型(prototype)解决方案是 B 扩展 A,如果这是您可以进行的可能修改:

function A() {
// empty constructor
}
A.prototype.msg = function() {
console.log("A");
}

class B extends A {
msg() {
console.log('b');
}
}

new B().msg();

(有了这个,内部原型(prototype)链看起来像:A.prototype -> B.prototype -> instance,所以从实例开始,B.prototype.msg优先于 A.prototype.msg)

关于JavaScript 从非 ES6 类覆盖到 ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832174/

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