gpt4 book ai didi

javascript - 类构造函数的调用函数

转载 作者:行者123 更新时间:2023-11-29 10:05:10 25 4
gpt4 key购买 nike

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

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;
}
}

关于javascript - 类构造函数的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44985825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com