Klejdi Sevdari
Klejdi Sevdari

Reputation: 19

Javascript. Why are not parentheses used when calling methods?

I was learning about React in Codecademy when I came across this example:

class MyClass extends React.Component {
   myFunc() {
     alert('Stop it.  Stop hovering.');
   }

   render() {
      return (
         <div onHover={this.myFunc}>
         </div>
   );
 }

I noticed that when myFunc is called, no parentheses were used and was wondering why. I would appreciate it if someone could explain it.

Upvotes: 0

Views: 666

Answers (2)

Jagannath
Jagannath

Reputation: 1

There are various event present on HTML elements like click, mouse hover etc. if you want to perform some action on hover on HTML element, then browser provide us these methods which will invoked when these action happens.

  • In above case on element hover browser will trigger/call myFunc method(onHover) handler
  • There is no need to call myFunc as it trigger on Hover event
  • OnHover handler should not be called inside render, otherwise it will be invoked every render which is incorrect

Upvotes: 0

&#211;scar Contreras
&#211;scar Contreras

Reputation: 105

You are only passing the reference to the function if you add () the function will execute every time your webpage is render

Upvotes: 2

Related Questions