【问题标题】:Why does my inherited static property not hold a value?为什么我继承的静态属性没有值?
【发布时间】:2018-02-23 00:32:41
【问题描述】:

我正在为我正在做的项目构建 ORM。我在 ORM 中有两个类,BaseModelSessionLink,以及它们外部的一个函数,它们都试图使用它们。 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 (class SessionLink extends BaseModel) 并添加了一些与此问题无关的特定于模型的细节。

我遇到的问题是:queryBuilder 没有它的价值。我可以从joinwhere 或任何地方运行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
  }
}

这是为什么?我该如何解决?

【问题讨论】:

  • 看来Query.addJoin 返回的不是 Query 实例。尝试拆分该行,例如 this.queryBuilder = new Query(); this.queryBuilder.addJoin(table)
  • 根据所谓的输出,new Query().addJoin(table); 似乎返回 null
  • 呃。你是对的,当然,@RobM。 - 我很笨,找错地方了,错过了我没有在addJoin 末尾添加return this 的事实。如果您想将其添加为答案,我会接受。

标签: javascript node.js class inheritance ecmascript-6


【解决方案1】:

您可以通过不实例化并在一行中调用addJoin 来解决此问题:

this.queryBuilder = new Query()
this.queryBuilder.addJoin(table)

或者通过您的addJoin() 方法返回this

class Query {
   addJoin(table) {
      // existing code
      return this
   }
}

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 1970-01-01
    • 2011-04-16
    • 2010-10-20
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    相关资源
    最近更新 更多