【问题标题】:How to bind function as a property of object如何将函数绑定为对象的属性
【发布时间】:2017-08-20 11:02:46
【问题描述】:

我有一个接受对象属性的函数,在这个对象中我想传递一个函数作为属性之一。我想在调用属性时执行该函数。我需要绑定函数,因为 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)
        }
      }
    })

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

【问题讨论】:

  • 也许我遗漏了一些东西,但不能将点击定义为箭头函数?例如click: () => console.log("someting")
  • 你现在的问题到底是什么?您能否展示您希望最终对象的外观?
  • 我现在遇到的问题是在第二种情况下,该函数永远不会被调用,即永远不会记录某些内容
  • @JaimeTorres 尝试了箭头功能,它实现了我想要的,谢谢!
  • 您有const self = this;,但没有在任何地方使用self。我假设您打算使用.bind(self)

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


【解决方案1】:

继续 @JamieTorres 建议的箭头函数解决问题

 const self = this;
   this.HeaderService.setState({
      leftButton: {
        click: () => {
           return (function () {
              console.log("something");
           }).bind(this)
        }
      }
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-16
    • 2020-06-22
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2011-10-03
    • 2020-02-11
    • 2011-03-04
    相关资源
    最近更新 更多