动态添加函数到 class 定义
Dynamically add functions to a class definition
我有一个库,我正在转换为使用 ES2015 语法并作为 ES 模块分发。
它公开了一个 class,其中的许多成员都是动态构造的。大量简化,它的结构是这样的:
class Utils {
// ...
}
extraFuncs.forEach(funcName => Utils.prototype[funcName] = makeFunc(funcName));
export default Utils;
(实际代码为here)。
有没有办法在不操纵原型的情况下实现方法的动态创建?
直接向 class 添加函数似乎没有任何效果。并且使用扩展运算符合并对象似乎也不起作用。
(我的动机之一是通过一个抱怨我正在做的事情的特定 lint 规则。)
Is there a way to achieve this dynamic creation of methods without manipulating the prototype?
没有。根据定义动态创建方法意味着扩展原型(除了 evil
方法)。
禁用该 linter 规则。
我有一个库,我正在转换为使用 ES2015 语法并作为 ES 模块分发。
它公开了一个 class,其中的许多成员都是动态构造的。大量简化,它的结构是这样的:
class Utils {
// ...
}
extraFuncs.forEach(funcName => Utils.prototype[funcName] = makeFunc(funcName));
export default Utils;
(实际代码为here)。
有没有办法在不操纵原型的情况下实现方法的动态创建?
直接向 class 添加函数似乎没有任何效果。并且使用扩展运算符合并对象似乎也不起作用。
(我的动机之一是通过一个抱怨我正在做的事情的特定 lint 规则。)
Is there a way to achieve this dynamic creation of methods without manipulating the prototype?
没有。根据定义动态创建方法意味着扩展原型(除了 evil
方法)。
禁用该 linter 规则。