Accessing `this` from the literal of the required object?

I want to have the following object type:

const Client = require('./Client')
let client = new Client()

client.someObject.create(...)
client.someObject.update(...)
client.someObject.delete(...)
etc.

      

This is very easy to do, for example:

const Client = function () {
  this.someObject = {}
  this.someObject.create = function () {...}
  this.someObject.update = function () {...}
  this.someObject.delete = function () {...}
}
module.exports = Client

      

But from an organizational point of view (and due to the large number of functions someObject

it would be useful to put all the content someObject

in its own file and require it:. require('./someObject')

However, I still have to be able to access the object Client

( this

) within someObject.create()

, someObject.update()

etc.

this.someObject = require('./someObject')

// someObject.js
module.exports = {
  create: function () {
    // How do I access Client here? Can I pass it to the object literal?
  }
}

      

I tried to make some kind of module type prototype but it doesn't work.

Client.prototype.someObject.create = function () { ... }

How can I highlight someObject

to my own file and still access the client this

?

+3


source to share


1 answer


You need to provide an instance Client

for someObject

, so later methods can use it to refer to the previous one.

One way you achieve this is by defining a 2nd constructor for someObject

which takes the client as an argument.

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);
}

      




You can also get a similar result with Object.create()

if you want to keep the object literal:

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);
};

      

+1


source







All Articles