类构造函数的调用函数

Sem*_*ram 4 javascript class async-await ecmascript-2017

有没有办法获取类的构造函数的调用函数?

class TestClass {
  constructor(options) {
    if(<caller> !== TestClass.create)
      throw new Error('Use TestClass.create() instead')
    this.options = options
  }

  static async create(options) {
    // async options check
    return new TestClass(options)
  }
}

let test = await TestClass.create()
Run Code Online (Sandbox Code Playgroud)

我试过了arguments.callee.callerTestClass.caller但出现以下错误:

Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them

Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
Run Code Online (Sandbox Code Playgroud)

在 Chrome 58 中测试

tri*_*cot 5

您可以通过不同的方式实现这一点:拒绝任何构造函数的使用,并让该create方法创建一个对象实例Object.create(它不会调用构造函数):

class TestClass {
    constructor() {
        throw new Error('Use TestClass.create() instead');
    }

    static async create(options) {
        // async options check
        const obj = Object.create(TestClass.prototype);
        obj.options = options;
        return obj;
    }
}
Run Code Online (Sandbox Code Playgroud)