Question about eventhandler function syntax in 7


#1

I’m currently on chapter 7 about “this.props”. The task is to move a function inside a class to act as a eventhandler. The original code was the following:

  function handleEvent() {
    alert(`I am an event handler.
      If you see this message,
      then I have been called.`);
  }

Moving this code into the class and building it works fine. However when looking at previous examples, eventhandlers does not have the function keyword. That is like this:

  handleEvent() {
    alert(`I am an event handler.
      If you see this message,
      then I have been called.`);
  }

And this code seems to compile just fine. What is the difference between using and not using the function keyword?


#2

I believe its just short hand. I ran into the same curiosity in the same Chapter. I want to say it also has something to do with declaring a function outside of the class component as a pose to inside the class component.


#3

its not just a shorthand, function handleEvent is fine on its own, but not as part of a class or react component. If we look at the documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

we see two ways to define a method (methods are functions inside a class). You need to use these ways, otherwise this keyword will never bind properly, causing problems.

Yes, the code runs fine. But its invalid syntax, if function handleEvent ever needs access to this, then you bound to have problems. So use valid method syntax.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.