Reactjs: In JavaScript, class methods are not bound by default
I think the React documentation might be misleading. The React component below MyClass
is a derived class (aka child class) of React.Component
. The constructor
method is a special method within javascript ES6 which is used for creating and initializing an object created with a class. React uses the constructor to pass props
to the component when the object is created. Base classes (aka parent classes) are created bound to their own this
, but the derived classes do not have their own this
by default. The derived class must call super(props) which binds the this
from the base class down into the derived class.
class MyClass extends React.Component{
constructor(props) {
super(props)
}
}
Here is the relevant information from the link provided by user376830's answer. This is straight from the javascript documentation.
Class context
The behavior of this
in classes and functions is similar, since classes are functions under the hood. But there are some differences and caveats.
Within a class constructor, this
is a regular object. All non-static methods within the class are added to the prototype of this
:
class Example {
constructor() {
const proto = Object.getPrototypeOf(this);
console.log(Object.getOwnPropertyNames(proto));
}
first(){}
second(){}
static third(){}
}
new Example(); // ['constructor', 'first', 'second']
Note: Static methods are not properties of this
. They are properties of the class itself.
Derived classes
Unlike base class constructors, derived constructors have no initial this
binding. Calling super()
creates a this
binding within the constructor and essentially has the effect of evaluating the following line of code, where Base is the inherited class:
this = new Base();
Warning: Referring to this before calling super()
will throw an error.
Derived classes must not return before calling super()
, unless they return an Object
or have no constructor at all.
class Base {}
class Good extends Base {}
class AlsoGood extends Base {
constructor() {
return {a: 5};
}
}
class Bad extends Base {
constructor() {}
}
new Good();
new AlsoGood();
new Bad(); // ReferenceError
When a function is used as an event handler, its 'this' is set to the element the event fired from. As a DOM event handler