在外部函数中存储super()?

时间:2018-05-17 05:14:24

标签: javascript oop

我正在制作一个系统,其中(ES6)类扩展另一个。它接收一个参数对象,其中一些需要提供给super()调用,因为它们在基类中是必需的,其他的稍后在构造函数中应用。事实是,由于这个系统将在许多类中使用,我想通过将该逻辑放在一个函数中来自动化该过程。但是,似乎我无法将super()放在任何不属于类的内容中。

我目前的情况如下:

class X extends Y {
    constructor(args) {
        applySuper(args, required_args);
        // args is an object 
        // required_args is a subset of args
    }
}

function applySuper(args, required_args) {
    // Uncaught SyntaxError: 'super' keyword unexpected here
    super(required_args.arg1, required_args.arg2, ...);

    // Find some way to separate the optional args and do something else with those... 
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我会用两个不同的功能来做到这一点:

class X extends Y {
    constructor(args) {
        super(...baseArgs(args));
        otherArgs(this, args);
    }
}

function baseArgs(required_args) {
    return [required_args.arg1, required_args.arg2, …];
}
function otherArgs(instance, args) {
    // Find some way to separate the optional args and do something else with those... 
}

那就是说,你可以super()调用放在箭头函数中并将其作为回调传递:

class X extends Y {
    constructor(args) {
        applyArgs(args, (...baseArgs) => {
            super(...baseArgs);
            return this;
        });
    }
}

function applyArgs(args, init) {
    const instance = init(args.arg1, args.arg2, …);
    // Find some way to separate the optional args and do something else with those... 
}

但实际上,如果多个类应该共享相同的行为,为什么不给它们相同的超类?

class Z extends Y {
    constructor(args) {
        super(args.arg1, args.arg2, …);
        // Find some way to separate the optional args and do something else with those... 
    }
}
class X extends Z {}