javascript - 是否需要用 new 来调用 es6 类?

标签 javascript ecmascript-6

我正在编写一个函数,它接受类并返回一个具有可扩展的单个类的类,但是我最近切换到 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 调用多个函数之类的?

最佳答案

100% 需要通过 new Constructor() 或通过 super() 调用 ES6 中的类构造函数。没有办法解决这个问题,因为这种行为对于 JavaScript 引擎能够构造正确类型的对象至关重要。

对于你的情况,假设 Circle 是

class Circle extends Array {}

你的代码将会被破坏,因为对象被创建

new Player()

不会是一个数组对象。这适用于任何 native 子类,也是 new 必要的原因。

如果您希望某些东西成为多组函数的组合,则需要从标准对象手动将这些函数组合在一起。

关于javascript - 是否需要用 new 来调用 es6 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442176/

相关文章:

javascript - laravel 如何链接外部 javascript 文件

javascript - Meteor Gravatar 出现在用户页面上,但不在房间列表中

javascript - 在 Js 文件中导入 jQuery 插件

javascript - 如何在有条件的情况下在另一个组件正下方的无状态组件上呈现函数?

javascript - 防止 jQuery one() 函数上的点击跳转

javascript - Angularjs 无法在 Nodejs Express 中工作

javascript - Bluemix 在出现下一个错误时崩溃

javascript - es6 如何使用非默认参数之前的默认参数?

javascript - 显示与 JSON 数据的 'Open Hours' 日期/时间对齐的 div

javascript - 无法从 Ionic2 的回调中访问本地属性