Class 构造函数的调用函数

Class constructor's caller function

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

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()

我已尝试 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.

测试 Chrome 58

您可以通过不同的方式实现此目的:只需拒绝使用构造函数,并让 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;
    }
}