2

The code below works, but my gut tells me this isn't the most succinct way to do this. I'd like to use this.function2() instead of videoControler.function2(), but that doesn't work. Is this the best way to write this?

const myController = {
  function1() {
    return res.json({
        blah: myController.function2()
    })
  },
  function2() {
    return "blah"
  }
}
user1661677
  • 1,252
  • 5
  • 17
  • 32

2 Answers2

0

In your example, replacing myController to this will point to currect scope, so it will not work. You should bind function1 to myController, and create reference to this outside the return state object, like const self = this;

0

Definitely check out @Teemu's link in the comment but another way to handle this is by using classes.

For instance:

class myController {
  constructor(type) {
    this.controllerType = type;
  }

  function1(x) {
    return res.json({
        blah: this.function2()
    });
  }

  function2(x) {
    return "blah";
  }
}

And this would follow the properties of OOP where you can instantiate a new myController("video") object and invoke functions belonging to the class, outside the class as well.

Jackson
  • 53
  • 1
  • 8