javascriptecmascript-6javascript-objectsfunction-binding

How to bind function as a property of object


I have a function which takes an object property, in this object I want to pass a function as one of the properties. I will like to execute the function when the property is called. I need to bind the function as the this context is lost before the function will be executed.

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

I can get the function expression to work, but I cant get the second case where I want to define the function as the value of the property click. How do i do this?


Solution

  • Continuing what @JamieTorres suggested an arrow function fixes the issue

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