When are Parentheses needed for calling methods?


#1

https://www.codecademy.com/en/courses/react-101/lessons/react-components-advanced-jsx/exercises/component-event-listener

In section 5, the lack of parentheses on the .food() method is reasoned by the presence of a “getter” method. However, section 6 does NOT use “get” and yet we still see the .scream() method without parentheses in the code:


{this.scream}

So what is the true reason for not using parentheses here? Or, is scream() somehow a getter method without actually using the “get” keyword?


#2

parentheses = ()
accolade/curly brackets = {}

{this.food} was just an example of a getter method, {this.scream} is also a getter method

i mean, simplifying the example:

3 + 2
4 + 3

both cases involves the plus operator, just like {this.scream} and {this.food} are both getter methods, any value could be used to teach you getter method or plus operator.


#3

stetim94, Thank you for your reply, but perhaps I did not state the issue clearly.

In Section 5, codecademy explains the reason for leaving off parentheses on the .food() method like this:

Why don’t you need parentheses after this.food? Shouldn’t it be this.food()?

You don’t need those parentheses, because .food is a getter method. You can tell this from the get in the above class declaration body.

However, in the next section, Section 6, the scream() method is defined without using the get keyword. If the above definition of a getter method is to be believed, the scream() method is not a getter method unless the get keyword is invoked.

Does that clarify my misunderstanding?


#4

hm… the instructions aren’t very clear about this matter

in React, you define event handlers as methods on a component class. Like this:

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

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

event handlers have the same syntax as getters, JS will make the distinguish between getter method and event handlers

seems i was a bit off, i am also still learning ReactJS into detail


#5

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