In classes, what is the difference between a function in the constructor vs a method?

class Hello {
  constructor() {
    this.func2 = function() {
      console.log("Hello World! 2");
    };
  }
  func() {
    console.log("Hello World!");
  }
}

Is there a difference between the two functions? What are the use cases of each?

The one in the constructor is [re]created every time the object is created

The one outside the constructor is attached to the prototype, only gets created once.

Note that you can use class properties instead of putting it in the constructor, is a bit less noisy:

class Hello {
  // function defined as class property, gets
  // created every time object is instantiated 
  func2 = () => {
    console.log("Hello World! 2");
  };

  // function defined on prototype, gets
  // created once when object is first instantiated 
  func() {
    console.log("Hello World!");
  }
}

Unless it’s really important that you recreate the function every time, don’t define it in the constructor as it defeats one of the main reasons for using a class in the first place

The usecase is if you are going to pass that method to something else & it’s really important that this in it refers to one specific instance of the object created by class.


Following may be quite difficult to follow, but here we go, an example:

This is common in some UI libraries (like React), but otherwise isn’t recommended unless you have a very good reason for doing it. Note that I’m using arrow functions as well, this is also important (means this refers to the parent scope, whereas a function created using function has its own this scope):

class Counter extends React.Component {
  state = {
    count: 0,
  }:

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  render() {
    return (
      <div>
        <p>Counter: {this.state.count}</p>
        <CounterButton onClick={this.increment} label="increment"/>
        <CounterButton onClick={this.decrement} label="decrement"/>
      </div>
    );
  }
}

class CounterButton extends React.Component {
  render() {
    return (
      <button type="button" onClick={this.props.onClick}>{this.props.label}</button>
    );
  }
}

If it isn’t done that way☝️, then this will get lost (when the button is clicked, it will look for this in the context of CounterButton, and the function won’t work). The function has to be specific to one instance of the Counter class

3 Likes

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