gpt4 book ai didi

javascript - 静态方法创建自己的实例

转载 作者:行者123 更新时间:2023-11-30 06:13:36 25 4
gpt4 key购买 nike

我正在尝试创建一个静态方法,该方法基本上创建自动进行调用的类的实例。

在这个例子中,我希望 A 类创建它自己的一个实例。如何才能做到这一点?下面的代码在执行时会报错。

class Model {
static find(someVar) {
let inst = new this.constructor[this.constructor.name]()
// Do some extra stuff with the instance
return inst
}
}

class A extends Model { }

A.find()

最佳答案

一个类的每个静态方法都有this上下文,它指向点之后的类

class Model {
static find(...args) {
console.log("My name is", this.name) // <- this will print "My name is AModel"
return new this(...args)
}
}

class AModel extends Model { }

AModel.find(); // <- passing `this` context to be the AModel class.

关于javascript - 静态方法创建自己的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402600/

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