Javascript 为什么继承的静态属性没有值?
我正在为我正在做的一个项目构建一个ORM。我在ORM中有两个类,Javascript 为什么继承的静态属性没有值?,javascript,node.js,class,inheritance,ecmascript-6,Javascript,Node.js,Class,Inheritance,Ecmascript 6,我正在为我正在做的一个项目构建一个ORM。我在ORM中有两个类,BaseModel和SessionLink,它们外部的一个函数都试图使用它们BaseModel是基本模型,其他模型从中继承,因此我可以定义常见行为SessionLink是继承的模型之一 我希望能够使用继承的模型从BaseModel链接查询方法。大概是这样的: SessionLink.join("a table").where({some: "conditions"}).get() 为了做到这一点,我需要在BaseModel上有一个
BaseModel
和SessionLink
,它们外部的一个函数都试图使用它们BaseModel
是基本模型,其他模型从中继承,因此我可以定义常见行为SessionLink
是继承的模型之一
我希望能够使用继承的模型从BaseModel
链接查询方法。大概是这样的:
SessionLink.join("a table").where({some: "conditions"}).get()
为了做到这一点,我需要在BaseModel
上有一个静态属性来存储通过链式方法建立的查询。到现在为止,一直都还不错。我已经将静态属性与getter和setter放在一起
class BaseModel {
static get queryBuilder() {
return this._query || null;
}
static set queryBuilder(val) {
this._query = val;
}
static join(table) {
if (this.queryBuilder) {
// Add to existing query
this.queryBuilder = this.queryBuilder.addJoin(table);
}
else {
// Create a new query, store it in queryBuilder
this.queryBuilder = new Query().addJoin(table);
}
}
static where(conditions) {
// Implementation similar to .join
}
static get() {
// Actually send the query to the database and return results
magicallyGetDatabaseConnection().sendQuery(this.queryBuilder);
}
}
SessionLink
只是继承了BaseModel
(类SessionLink扩展了BaseModel
),并添加了一些与此问题无关的特定于模型的详细信息
我遇到的问题是:queryBuilder
不保存其值。我可以从join
或where
或任何地方运行this.queryBuilder=new Query(…)
,然后在下一行记录this.queryBuilder
的值,它返回为null
。换言之:
static join(table) {
if (this.queryBuilder) {
// Add to existing query
this.queryBuilder = this.queryBuilder.addJoin(table);
}
else {
// Create a new query, store it in queryBuilder
this.queryBuilder = new Query().addJoin(table);
console.log(this.queryBuilder); // null
}
}
为什么会这样?如何修复它?您可以通过不在一行中实例化和调用
addJoin
来解决此问题:
this.queryBuilder = new Query()
this.queryBuilder.addJoin(table)
或者从addJoin()
方法返回this
class Query {
addJoin(table) {
// existing code
return this
}
}
似乎
Query.addJoin
返回的不是查询实例。尝试拆分该行,例如this.queryBuilder=newquery();this.queryBuilder.addJoin(table)
根据声称的输出,似乎newquery().addJoin(table)代码>返回null
Ugh。当然,你是对的,罗宾我装傻了,找错了地方,错过了添加失败的事实,将此返回到addJoin
的末尾。如果你想加上这个作为回答,我会接受的。