0

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?

Abhishek
  • 1,477
  • 1
  • 10
  • 18
lboyel
  • 1,930
  • 4
  • 27
  • 37
  • 1
    Maybe I'm missing something, but can't use just define click as an arrow function? e.g. `click: () => console.log("someting")` – Jaime Torres Mar 27 '17 at 16:18
  • What exactly is the problem with what you have now? Can you show how you want your final object to look? – Aron Mar 27 '17 at 16:19
  • the problem I have now is in the second case the function is never called, i.e something is never logged – lboyel Mar 27 '17 at 16:20
  • @JaimeTorres tried the arrow function and it achieves what I want, thanks! – lboyel Mar 27 '17 at 16:31
  • You have `const self = this;`, but are not using `self` anywhere. I assume you meant to use `.bind(self)`. – Felix Kling Mar 27 '17 at 16:40
  • Possible duplicate of [How to access the correct `this` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Felix Kling Mar 27 '17 at 16:40

1 Answers1

0

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)
        }
      }
    })
lboyel
  • 1,930
  • 4
  • 27
  • 37