绕过了用new调用es6类的方法



我正在编写一个函数,它接受类并返回一个类,其中包含一个可以扩展的类,但是我最近切换到babel转译器,并意识到我不应该在没有new的情况下调用类构造函数,

是否有一种方法可以在实际的es6中工作?

这是我的多重函数

Object.getOwnPropertySymbols;
module.exports = function multiple(_classes){
    class MultipleClasses{}
    for (const {obj:_class} of iterateObject(_classes)){
        const prototypeChain = [];
        let prototype = _class.prototype;
        do{
            prototypeChain.push(prototype);
        }
        while((prototype = prototype.__proto__) !== null)
        prototypeChain.reverse();
        for (const prototype of prototypeChain){
            assignNonEnumerable(MultipleClasses.prototype, prototype);
        }
    }
    for (const {key, obj:_class} of iterateObject(_classes)){
        MultipleClasses.prototype[key] = _class.prototype.constructor;
    }
    return MultipleClasses;
}
function* iterateObject(obj){
    const keys = Object.getOwnPropertyNames(obj);
    for (const key of keys){
        yield {key, obj:obj[key]};
    }
}
function assignNonEnumerable(target, source){
    const keys = Object.getOwnPropertyNames(source);
    for (const key of keys){
        Object.defineProperty(target, key, {
            enumerable:false,
            writable:true,
            configurable:true,
            value:source[key]
        });
    }
    const symbols = getOwnPropertySymbols(source);
    for (const symbol of symbols){
        Object.defineProperty(target, symbol, {
            enumerable:false,
            writable:true,
            configurable:true,
            value:source[symbol]
        }); 
    }
}

和扩展类我使用

class Player extends multiple({Physical, Circle}) {
    constructor(_x, _y, input){
        super();
        super.Physical(_x, _y)
        super.Circle(_x, _y, playerRadius);
...

是否有办法让super调用多个函数或其他东西?

在ES6中100%要求通过new Constructor()super()调用类构造函数。没有办法绕过它,因为这种行为对于JavaScript引擎能够构造正确类型的对象是至关重要的。

在你的例子中,Circle was

class Circle extends Array {}

你的代码会中断,因为

创建的对象
new Player()

将不是数组对象。这适用于任何本地子类,也是new是必需的原因。

如果你想要一些东西是许多函数集合的组合,你需要从标准对象中手动将这些函数组合在一起。

尽管new可能是"危险的",但如果您使用某些保护构造类,则仍然可以使用类。是的,这有点古怪,"好部分"主义者对此嗤之以鼻,但我觉得总的来说,课程仍然是一个胜利。

class Player {
  constructor(/*args...*/) {
    if(!(this instanceof Player)) {
      return new Player(/*args...*/);
    }
  }
}
var player1 = Player("Spencer");
var player2 = new Player("Other guy")

最新更新