Home > Enterprise >  does constructor allow to bind undefined method?
does constructor allow to bind undefined method?

Time:10-28

I am studying react and following the guide: event handling section, and watching binding of an event handler to a class in a constructor. There's a thing I want to understand. Why is it's okay to bind yet undefined method of a class in the constructor? or are methods of a class initialized before the constructor? or algoritm of class intialization starts with the constructor but it's possible to define already binded function later?

  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
...

CodePudding user response:

Function definitions in classes are initialized before the constructor runs. Here's an example:

class Bar {
  constructor(props) {
    console.log('Bar constructor');
    console.log(props);
  }
}

class Foo extends Bar {
  constructor(props) {
    super(props);
    console.log('Foo constructor');
    console.log(this.handleClick);
    
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this);
  }
}

const foo = new Foo({a: 1});

console.log('`this` in handleClick:');
foo.handleClick();
.as-console-wrapper { max-height: 100% !important; }

  • Related