我试图创建一个可以处理基本CRUD函数的父类,但我无法弄清楚如何在静态方法中调用构造函数。
class Model {
static find(id) {
var attrs = someDBcalls();
var obj = new CurrentClass(attrs); // how?
return obj;
}
}
class User extends Model {
constructor(attrs){
// initialize class.
}
}
User.find(1); // shall return an User object.
答案 0 :(得分:1)
您可以使用var obj = new this(attrs);
,如下所示:
function someDBcalls(id) {
return { id, success: true };
}
class Model {
static find(id) {
var attrs = someDBcalls(id);
var obj = new this(attrs);
return obj;
}
}
class User extends Model {
constructor(attrs) {
super();
// initialize class.
console.log(attrs);
}
}
var user = User.find(1); // shall return an User object.
console.log(user instanceof User);