使用标准 es5 我有这个方法允许我将方法添加到我的库的原型(prototype)链(它允许扩展核心库以及附加到库的任何组件):
library.extend = function(extendId, extendObj) {
//if it's an extension of the core library object...
if(extendId === 'library') {
library.prototype[extendObj.name] = extendObj.func;
} else {
library.component[extendId].prototype[extendObj.name] = extendObj;
}
};
用法是:
/* create some new class */
var somecomponent = function() {}
somecomponent.protoype.somemethod = function() {}
/* extend the base libraries prototype chain with the new class*/
library.extend('library', somecomponent)
在 es6 类中,我们也有原型(prototype),但它们被类语法屏蔽了,您应该使用 extends
方法向类添加方法。
因此,我不确定如何使用与上述类似的方法以编程方式向 es6 类添加方法。
最佳答案
我觉得你有些困惑。
在 ES5 中,使用 function
表达式或声明创建的函数都是可实例化的(即构造函数)和可调用的:
function f() {}
f(); // Function call
new f(); // Constructor instantiation
然后 ES6 允许创建只能调用或只能实例化的对象:
var f = () => {}; // Arrow function
f(); // Function call
new f(); // Error: f is not a constructor
class f {}; // Class
f(); // Error: Cannot call a class as a function
new f(); // Constructor instantiation
也就是说,ES6 类只是具有 [[Construct]] 内部方法和 prototype
属性的对象。您可以将它们完全视为 ES5 构造函数。
所以用法是
class somecomponent { /* create some new class */
somemethod() {}
}
/* extend the base libraries prototype chain with the new class*/
library.extend('library', somecomponent)
其中 library.extend
是当前的。
关于javascript - 以编程方式扩展 es6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33754152/