在对象中引用另一个方法的正确方法

下面的代码有效,但我的直觉告诉我这不是最简洁的方法。我想使用this.function2()而不是videoControler.function2(),但这不起作用。这是写这个的最好方法吗?


const myController = {

  function1() {

    return res.json({

        blah: myController.function2()

    })

  },

  function2() {

    return "blah"

  }

}


千巷猫影
浏览 189回答 2
2回答

函数式编程

一定要查看评论中的@Teemu 链接,但另一种处理方法是使用类。例如:class myController {  constructor(type) {    this.controllerType = type;  }  function1(x) {    return res.json({        blah: this.function2()    });  }  function2(x) {    return "blah";  }}这将遵循 OOP 的属性,您可以在其中实例化一个new myController("video")对象并调用属于该类的函数,也可以在该类之外调用。

慕神8447489

在您的示例中,将 myController 替换为 this 将指向当前范围,因此它将不起作用。您应该将 function1 绑定到 myController,并在返回状态对象之外创建对 this 的引用,例如 const self = this;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript