【问题标题】:Is it possible to indirectly call the constructor function where X is an ES6 class? [duplicate]是否可以间接调用 X 是 ES6 类的构造函数? [复制]
【发布时间】:2020-10-21 16:13:36
【问题描述】:

这与an old question 有关,但我特意询问如何使用旧的编写函数的方式扩展一个新的 ES6 类。

以下代码不起作用。

class X {
    a;
    constructor(a) {
        this.a = a;
    }
}
X.call({}, 3); // Uncaught TypeError: Class constructor X cannot be invoked without 'new'

有没有办法间接调用构造函数?例如,我是否可以使用老式的原型继承来制作 Y?

function Y(a) {
    X.call(this, a); // this doesn't work here, can't use super as well
}
Y.prototype = Object.create(X.prototype);
Object.setPrototypeOf(Y, X);
const y = new Y(12);

【问题讨论】:

  • 我很好奇,当您扩展使用class 创建的构造函数并且您使用的是ES2015+ 时,为什么要使用传统函数而不是class

标签: javascript ecmascript-6


【解决方案1】:

是的,您可以使用Reflect.constructnew.target

function Y(a) {
    return Reflect.construct(X, [a], new.target || Y);
}

现场示例:

class X {
    a;
    constructor(a) {
        this.a = a;
    }
}

function Y(a) {
    return Reflect.construct(X, [a], new.target || Y);
}
Y.prototype = Object.create(X.prototype);
Object.setPrototypeOf(Y, X);
const y = new Y(12);
console.log(y.a); // 12

或者如果你想传递所有提供的参数:

function Y(...args) {
    return Reflect.construct(X, args, new.target || Y);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2022-01-08
    • 1970-01-01
    • 2014-12-17
    • 2021-05-09
    相关资源
    最近更新 更多