Class constructor call function
Is there a way to get the caller function of a class 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 tried arguments.callee.caller
and TestClass.caller
, but I got 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
+3
source to share
1 answer
You can achieve this in a different way: just ditch the use of a constructor, and let the method create
instantiate an object with Object.create
(which won't 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;
}
}
+4
source to share