【问题标题】:Class constructor's caller function类构造函数的调用函数
【发布时间】:2017-12-12 15:21:55
【问题描述】:

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

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 中测试

【问题讨论】:

    标签: javascript class async-await ecmascript-2017


    【解决方案1】:

    您可以通过不同的方式实现这一点:拒绝任何构造函数的使用,并让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;
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2018-02-28
    • 2011-12-07
    • 2019-03-14
    相关资源
    最近更新 更多