Javascript 从所需的对象文本中访问“this”?
我希望拥有以下类型的对象:Javascript 从所需的对象文本中访问“this”?,javascript,object,Javascript,Object,我希望拥有以下类型的对象: const Client = require('./Client') let client = new Client() client.someObject.create(...) client.someObject.update(...) client.someObject.delete(...) etc. 这样做很容易做到: const Client = function () { this.someObject = {} this.someObjec
const Client = require('./Client')
let client = new Client()
client.someObject.create(...)
client.someObject.update(...)
client.someObject.delete(...)
etc.
这样做很容易做到:
const Client = function () {
this.someObject = {}
this.someObject.create = function () {...}
this.someObject.update = function () {...}
this.someObject.delete = function () {...}
}
module.exports = Client
但是从组织的角度来看(并且由于someObject
拥有大量的功能,将所有someObject
内容放入它自己的文件并要求它:require('./someObject')
。但是,我仍然需要能够访问客户机对象(this
)在someObject.create()
,someObject.update()等中
this.someObject = require('./someObject')
// someObject.js
module.exports = {
create: function () {
// How do I access Client here? Can I pass it to the object literal?
}
}
我尝试过做一些原型子模块类型的设置,但似乎不起作用
Client.prototype.someObject.create=function(){…}
如何将someObject
分离到它自己的文件中,并且仍然访问客户端this
?您需要向someObject
本身提供客户端
实例,以便后者的方法可以使用它引用前者
实现这一点的一种方法是为someObject
定义第二个构造函数,将客户机作为参数
const SomeObject = function (client) {
if (!client) throw new Error('Client reference is required.');
this.client = client;
};
SomeObject.prototype.create = function () {
let client = this.client;
// ...
};
// ....
module.exports = SomeObject;
如果您希望保留对象文字,还可以使用Object.create()
获得类似的结果:
const baseline = {
create: function () {
let client = this.client;
// ...
},
// ...
};
module.exports = function createSomeObject(client) {
return Object.create(baseline, {
client: {
value: client
}
});
};
它可能需要循环引用。可能this.someObject={client:this};
。然后,create
等可以使用this.client
。我不明白:现在,当调用client.someObject.create()时
,这个
等于某个对象
,而不是客户端
@le\m是的。在某个对象中,我会称它为客户端
或其他什么。我只想在某个对象中找到一种访问它的方法。不管它叫什么。@JonathanLonowski谢谢你。我考虑过这一点,但保留这个就好了另一个文件中的bject
定义。如果它是一个函数而不是一个对象文本,我可以将它传递到函数中,这会有什么不同吗?@JakeWilson我指的是你的“做这样的事情很容易做到”-例如。您当前如何访问客户端的此
,例如创建
?啊,伙计,我想太多了。感谢您为我指出了正确的方向。我想在这种情况下不必使用对象文字。谢谢,@JakeWilson,如果您愿意继续使用对象文字,我添加了一个替代方案。
const baseline = {
create: function () {
let client = this.client;
// ...
},
// ...
};
module.exports = function createSomeObject(client) {
return Object.create(baseline, {
client: {
value: client
}
});
};
const createSomeObject = require('./someObject');
const Client = function () {
this.someObject = createSomeObject(this);
};