从所需的对象文字中访问`this`?

时间:2017-05-20 22:01:48

标签: 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.someObject.create = function () {...}
  this.someObject.update = function () {...}
  this.someObject.delete = function () {...}
}
module.exports = Client

但是从组织的角度来看(并且由于someObject具有大量功能,将所有someObject内容放入其自己的文件中并将其需要:{{1}但是,我仍然需要能够访问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? } }

如何将Client.prototype.someObject.create = function () { ... }分隔到自己的文件中并仍然访问客户端someObject

1 个答案:

答案 0 :(得分:1)

您需要向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);
};