如何修改 ES6 的构造函数 class

How to modify the constructor of an ES6 class

我正在尝试使用 ES6 classes 进行热代码重新加载。我需要能够修改 classes 的构造函数,而不需要将 class 替换为新构造函数(因为其他人可能会引用它)。

但是,我发现 class 对象似乎对最初定义的构造函数有一些内部引用;用 new 实例化 class 不会在 class.

上查找 constructorprototype.constructor

示例:

class OldC { constructor() { console.log("old"); } }
class NewC { constructor() { console.log("new"); } }

OldC.prototype.constructor = NewC.prototype.constructor;
OldC.constructor = NewC.constructor;
new OldC();

---> "old"

(更新所有其他方法都可以正常工作;只是我遇到问题的构造函数。)

认为构造函数可能是通过 [[prototype]] 找到的,我还添加了这个:

Object.setPrototypeOf(OldC, Object.getPrototypeOf(NewC));
Object.setPrototypeOf(OldC.prototype, Object.getPrototypeOf(NewC.prototype));

这也无济于事(考虑到没有 subclassing 正在发生,我不会期望它有帮助)。

毕竟,检查 OldC 表明原型属性完全符合我的预期,OldC.prototype.constructor 是新的。但是,构造 OldC 的实例仍然会调用原始构造函数。

这是怎么回事,我该如何解决?

Still, constructing an instance of OldC calls the original constructor.

是的,因为OldC本身就是构造函数。您需要覆盖 OldC 变量以更改 new OldC 的作用。

Modify a classes' constructor, without replacing the class with a new one (because other people may have a reference to it).

正如@trincot 在评论中指出的那样,you cannot modify the code of a function。你必须用一个新的构造函数来替换它,没有办法解决它。

不过您可以保留原型对象(它是可变的),因为这是大多数其他事物(尤其是旧实例)将引用的内容。

NewC.prototype = OldC.prototype;
NewC.prototype.constructor = NewC;
OldC = NewC;

那些引用了现在无法更改的旧构造函数的人无能为力。你最好的选择是根本不分发 class 本身,而只分发一个你的更新代码知道要修改其行为的工厂。