我有一个在 Node.js 应用程序中使用的外部库 ( Objection.js )。我创建了一个基本模型类,它为我的实体模型扩展了 Objection 的 Model
类:
const { Model } = require('objection')
class ModelBase extends Model {
// implementation not important for this question
}
在扩展我的基类的模型类中,有时,特别是在编写 relationMappings
时,我必须访问 Model
基类上的属性/枚举。我可以在我的扩展模型中这样做:
const ModelBase = require('./model-base')
class SomeModel extends ModelBase {
static get relationMappings () {
const SomeOtherModel = require('./some-other-model')
trở lại {
someOtherModel: {
relation: ModelBase.BelongsToOneRelation,
modelClass: SomeOtherModel,
// etc.
}
}
}
}
Để ýrelation: ModelBase.BelongsToOneRelation
行。这是可行的,但我认为它具有误导性,因为 BelongsToOneRelation
KHÔNG ModelBase
的成员。对我来说更明确和正确的是从 Objection 导入/需要 Model
,这样我就可以从那里访问 BelongsToOneRelation
,例如:
const { Model } = require('objection')
// other code just like above until the relationMappings...
relation: Model.BelongsToOneRelation
我更喜欢这种方法。如果我导入/需要一个已经在继承链范围内的类,它会导致问题,例如 require 循环或循环依赖的 JavaScript 版本吗?
Will it cause problems, like require loops or the JavaScript version of a circular dependency, if I import/require a class that is already in scope in the inheritance chain?
没有。模块将在第一次需要时执行,然后如果执行完成,exports
对象将被缓存,并且进一步的 require()
将返回相同的对象。
如果有循环依赖,其中一个 require()
会在模块执行之前返回导出对象,因此此时导出对象将为空,但会被填充稍后再介绍属性。
因此,即使是循环依赖也可能正常工作,但如果它们失败,则会导致您头痛,因此请尽量避免导致这种情况。
Tôi là một lập trình viên xuất sắc, rất giỏi!