我希望具有以下类型的对象:
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
但是从组织的 Angular 来看(由于
someObject
具有大量功能,将所有someObject
内容放入其自己的文件中并需要它是有帮助的:require('./someObject')
。但是,我仍然需要能够访问Client
对象(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?
}
}
我尝试做一些原型(prototype)子模块类型的设置,但似乎没有用。
Client.prototype.someObject.create = function () { ... }
如何将
someObject
分离到它自己的文件中,仍然访问客户端this
? 最佳答案
您需要为Client
本身提供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;
const SomeObject = require('./someObject');
const Client = function () {
this.someObject = new SomeObject(this);
}
如果您希望保留对象字面量,也可以使用
Object.create()
获得类似的结果: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);
};
关于javascript - 从所需对象文字中访问 `this`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44091215/