如何将函数绑定为对象的属性

时间:2017-03-27 16:14:37

标签: javascript ecmascript-6 javascript-objects function-binding

我有一个带有对象属性的函数,在这个对象中我想传递一个函数作为其中一个属性。我想在调用属性时执行该函数。我需要绑定函数,因为在执行函数之前,此上下文已丢失。

    var myfunction = function () {
       console.log("Something");
    }

    // this works
    this.HeaderService.setState({
      leftButton: {
        click: this.myfunction.bind(this)
      }
    });

    // can't get this to work
    const self = this;
    this.HeaderService.setState({
      leftButton: {
        click() {
           return (function () {
              console.log("something");
           }).bind(this)
        }
      }
    })

我可以让函数表达式工作,但我不能得到第二种情况,我想将函数定义为属性click的值。我该怎么做?

0 个答案:

没有答案