0

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

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

我可以让函数表达式工作,但我无法获得第二种情况,我想将函数定义为属性单击的值。我该怎么做呢?

4

1 回答 1

0

继续@JamieTorres 建议的箭头功能解决了这个问题

 const self = this;
   this.HeaderService.setState({
      leftButton: {
        click: () => {
           return (function () {
              console.log("something");
           }).bind(this)
        }
      }
    })
于 2017-03-27T16:45:00.787 回答