1

If I compose some methods with factory function below.

function createCrudMethods() {
  return {
    findMany: async () => {
    },
    findOne: async () => {
    },
    createOne: async () => {
    },
    deleteOne: async () => {
    },
    updateOne: async () => {
    },
  };
}

Can I do something like this?

const object = {
  ...createCrudMethods();
  createOneWithNumber() {
    // do some cool stuff
    createOne() // error undefined
  }
}

or maybe there is a better way to do this?

Pu5her
  • 53
  • 4

1 Answers1

4

You can make use of function scope to refer to yourself using this:

function createCrudMethods() {
  return {
    findMany: () => console.log('findMany'),
    findOne: () => console.log('findOne'),
    createOne: () => console.log('createOne'),
    deleteOne: () => console.log('deleteOne'),
    updateOne: () => console.log('updateOne')
  };
}

const object = {
  ...createCrudMethods(),
  createOneWithNumber() {
    // do some cool stuff
    console.log('createOneWithNumber');
    this.createOne();
  }
};

// Console should show:
// - createOneWithNumber
// - createOne
object.createOneWithNumber();
AngYC
  • 3,051
  • 6
  • 20
  • 2
    This wasn't an anonymous function. It will work fine with the previous syntax – Konrad Apr 26 '23 at 09:41
  • 3
    `{ createOneWithNumber() { } }` is basically the shorthand of `{ createOneWithNumber: function() { } }` [How does this object method definition work without the "function" keyword?](https://stackoverflow.com/q/32404617) – VLAZ Apr 26 '23 at 09:42
  • 2
    My apologies, yup @Konrad and @VLAZ is right, the only change needed is the `this.` keyword, thanks for correction! – AngYC Apr 26 '23 at 09:44