Javascript 以编程方式扩展es6类

Javascript 以编程方式扩展es6类,javascript,ecmascript-6,Javascript,Ecmascript 6,使用标准es5,我可以使用此方法将方法添加到库的原型链(它允许扩展核心库以及附加到库的任何组件): 用途如下: /* create some new class */ var somecomponent = function() {} somecomponent.protoype.somemethod = function() {} /* extend the base libraries prototype chain with the new class*/ library.exte

使用标准es5,我可以使用此方法将方法添加到库的原型链(它允许扩展核心库以及附加到库的任何组件):

用途如下:

 /* 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类中,我们也有原型,但它们被类语法屏蔽,您应该使用
extends
方法向类中添加方法

因此,我不确定如何使用类似于上面所述的方法以编程方式向es6类添加方法

在es6类中,我们也有原型,但它们被类语法屏蔽,您应该使用
extends
关键字向类中添加方法

我不知道你说的“蒙面”是什么意思。是的,它的语法不同,但结果是完全相同的-
创建了一个带有
.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
是当前代码。

如果不显示如何使用此代码,很难理解您的要求。然而。。。通常,ES2015类可以被认为是“正常”(ES5)函数。您应该能够扩展原型。类更不只是语法上的糖分。@Amit我添加了一个用法示例,虽然我认为代码本身就说明了问题……它只是扩展了一个原型链。@webduvet-所以我应该继续直接扩展原型,然后。。。
class somecomponent { /* create some new class */
  somemethod() {}
}

/* extend the base libraries prototype chain with the new class*/
library.extend('library', somecomponent)