我想要一个主类,其中包含从附加到它的许多其他函数派生的方法。所以说我有
class MasterObject {
method1...,
method2...,
etc...
}
使用 ES6,id 喜欢导入这些函数以作为方法分配给 MasterClass。所以我尝试了这样的事情:
function setUpObj (...fns) {
class MasterObj {
constructor (...args) {
Object.assign(this, args)
}
}
return new MasterObj(fns)
}
let master = setUpObj(square, add, divide)
master.square(1,2)
当我这样做时,方法实际上并没有分配给对象(我假设它们分配给了 this,但不是作为方法)。显然我不明白原型(prototype)继承是如何工作的,所以如果你能用 ES6 类来解释它,那将对我有很大帮助。
相关: https://gist.github.com/allenwb/53927e46b31564168a1d ES6 Class Multiple inheritance
最佳答案
Object.assign
接受一个包含要复制的属性的对象。在你的例子中,你传递给它一个数组,这意味着你将 square
作为 master[0](1, 2)
。如果你想让它们命名,你需要用名字传递它们,例如
function setUpObj (fns) {
class MasterObj {
constructor (args) {
Object.assign(this, args);
}
}
return new MasterObj(fns)
}
let master = setUpObj({square, add, divide})
master.square(1, 2);
就是说,这个设置看起来有点奇怪,因为您每次都重新声明类。也许这样的事情会更清楚:
function setUpObj (fns) {
class MasterObj {
}
Object.assign(MasterObj.prototype, fns);
return MasterObj;
}
let MasterObjWithFunctions = setUpObj({square, add, divide})
let master = new MasterObjWithFunctions();
master.square(1, 2)
关于javascript - 在 ES6 中为类分配多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260833/