简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM