4

Is there a way to get the caller function of the class's constructor?

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

I've tried arguments.callee.caller and TestClass.caller but I get the following error:

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.

Testing in Chrome 58

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

1 Answers1

5

You could achieve this in a different way: just refuse any use of the constructor, and let the create method create an object instance with Object.create (which will not call the constructor):

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;
    }
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • So pity this method doesn't work on class fields declaration... Maybe it's because that it's just a syntax sugar for constructor... https://github.com/tc39/proposal-class-fields – kuanyui Mar 03 '20 at 08:14