Javascript 如何访问';这';在要求的模块内?
我试图制作一个模块,作为特定站点的API包装器。出于组织目的,有一个包含API类的中心文件,该类在构造函数中运行一些逻辑,并需要包含与API交互的函数的文件,这些文件根据Javascript 如何访问';这';在要求的模块内?,javascript,node.js,this,Javascript,Node.js,This,我试图制作一个模块,作为特定站点的API包装器。出于组织目的,有一个包含API类的中心文件,该类在构造函数中运行一些逻辑,并需要包含与API交互的函数的文件,这些文件根据lib目录中的类别分为不同的文件 [API.js] const Search = require('./lib/search'), Character = require('./lib/character') ... class API { constructor(apikey, options =
lib
目录中的类别分为不同的文件
[API.js]
const Search = require('./lib/search'),
Character = require('./lib/character')
...
class API {
constructor(apikey, options = {}) {
/* some logic... */
this.endpoint = 'https://some.site/'
this.globalQueries = {
key: apikey,
language: options.lang || 'en',
...
}
this.search = new Search()
this.character = new Character()
...
}
}
module.exports = API
我想做的是在所有需要的文件(可能不是正确的措辞)中从此作用域访问this
,以便,例如,/lib/character
的内容
[lib/character.js]
const request = require('request-promise-native')
class Character {
constructor() {}
look(name, params = {}) {
request({
uri: this.endpoint + 'character/look',
qs: Object.assign(this.globalQueries, params),
json: true
}).then((res) => {
...
}
}
module.exports = Character
然后,不仅对this.endpoint
和this.globalquerys
的所有引用都会正常工作,而且API.jsthis
中的任何其他元素也会正常工作,并确保在调用时为每个函数检索值,以便对任何更改都是最新的
我不知道如何实现这一点,因此非常感谢您的帮助。您可以将父实例作为参数传递给每个构造函数,如下所示:
class Character {
constructor (parent) {
this.parent = parent
}
look (name, params = {}) {
request({
uri: this.parent.endpoint,
qs: Object.assign(this.parent.globalQueries, params),
json: true
})
}
}
然后,在API类定义中:
class API {
constructor(apikey, options = {}) {
/* some logic... */
this.endpoint = 'https://some.site/'
this.globalQueries = {
key: apikey,
language: options.lang || 'en',
...
}
this.search = new Search(this)
this.character = new Character(this)
...
}
}
就我个人而言,我认为最好在构造函数中指定您对字符和搜索的需求,以便更清晰、更容易理解。所以它可以看起来像那样
class API {
constructor(apikey, options = {}) {
/* some logic... */
const context = {
endpoint: 'https://some.site/',
globalQueries: {
key: apikey,
language: options.lang || 'en',
},
}
this.context = context;
this.search = new Search(context)
this.character = new Character(context)
}
}
class Character {
constructor (context) {
this.context = context
}
look (name, params = {}) {
request({
uri: this.context.endpoint,
qs: Object.assign(this.context.globalQueries, params),
json: true
})
}
}
因此,上下文对象将在类
API
中的父对象及其子对象之间共享,该指向API
实例。但是还没有创建实例,所以很难知道您要访问什么。谢谢。我最初是在寻找一种解决方案,使调用this.endpoint能够独立工作,而不需要父部分,就像我在其他应用程序中看到的那样。然而,我刚刚发现这些情况是通过Function.prototype.bind()实现的,我想在我的用例中实现它并不像我想象的那么容易。我将您的答案标记为正确,因为这似乎是更好的方法:)我喜欢在两个文件上以相同的方式访问它,所以这不是子文件中的this.context.element
,而父文件中的this.element
!谢谢