我有一些 es6 类
class Human {
constructor(){
this.age = 0;
}
}
我想使用dojo工具包继承这个类
define(["dojo/_base/declare"],
function (declare) {
return declare("Man", Human, {
});
});
我收到错误没有“new”就无法调用类构造函数 Human
。
尝试从 Human.constructor
和 Human.funcWrapper
继承
class Human {
constructor(){
this.age = 0;
}
static funcWrapper(){
return new Human()
}
}
没有任何作用。
我知道我可以使用 babel 将代码转换为函数,但由于某些政治原因我不想这样做。
最佳答案
像往常一样,我会在帖子中敲了几个小时,然后我提出了一个解决方案。到目前为止,我已经对其进行了测试,看起来效果很好。包括调用 this.inherited(arguments, ["bla"])
(dojo 调用 super("bla")
的方式)
所以,我创建了这个函数来将 es6 类转换为函数类
function funcClass(type) {
const FuncClass = function (...args) {
const _source = Reflect.construct(type, args, this.constructor);
const keys = Reflect.ownKeys(_source);
for (const key of keys) {
if (!key.match || !key.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)) {
const desc = Object.getOwnPropertyDescriptor(_source, key);
!this[key] && Object.defineProperty(this, key, desc);
}
}
}
FuncClass.prototype = type.prototype;
return FuncClass;
}
及用法:
define(["dojo/_base/declare"],
function (declare) {
return declare("Man", funcClass(Human), {
});
});
关于javascript - 如何使用 Dojo 扩展 es6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46581433/