Classes in React using this

Why is “this” defined in this javascript class:

while “this” is undefined here in React?

Screen Shot 2019-12-06 at 13.50.26

Just in future, please post code, not pictures of code.

It’s not undefined.

It’s the same as

class Counter extends Component {
  constructor (props) {
    super(props);
    this.count = 0;
  }

  handleIncrement() {
    ...

It doesn’t need any initialisation logic (ie doing something with props before state gets created) so this.state can be initialised as a class property with that value of 0 for count.

1 Like

Check out this article: This is why we need to bind event handlers in Class Components in React,
it should clear things for you, hopefully!

1 Like

The console.log logs “undefined” for “this”, does it not?

Thank you… I wonder if you can answer one question pertaining to this article. In the following code, why do we bind to “this” and not bind to something like (Foo)? Doesn’t “this” represent our instance of Foo?

class Foo {
  constructor(name){
    this.name = name
    this.display = this.display.bind(this);
  }
  
  display(){
    console.log(this.name);
  }
}

var foo = new Foo('Saurabh');
foo.display(); // Saurabh

var display = foo.display;
display(); // Saurabh

Yes, this is the instance, but that’s what you need to bind to. The class definition is just a template used to create objects, it’s not really a concrete thing. And logically, how could it work: what would happen if you had 200 instances of Foo? Or even just two?

Gotcha, we need to reference the specific instance… Appreciate your help today. I’m just trying to shore up some minor problems with my fundamental understanding of Javascript.

In React, do we use super( ) here because class Counter is an extension of Component?


class Counter extends Component {
   state = { count: 0  };    
   
  constructor( ) {
     super( );
     this.handleIncrement = this.handleIncrement.bind(this);
     }

  handleIncrement() {
   console.log("Increment Clicked", this);



}
````````````````````````````````````````````````````````````````````````````````````````````````` 

Yes, we do, it allows you to call functions on the parent.

LAST QUESTION - Do you mean that Counter is the parent of the constructor or that Component is a parent of Counter, or both?

Counter inherits from the React.Component class. The React.Component class has several functions (for example componentDidMount, render and so on) which you get access to when you inherit from it. The super() function is literally calling the parent constructor function.

You can also use arrow functions as they are automatically binded.