So, I understand using =>
function can help do the static binding of the method with the class.
But, what I don't understand is the opposite, why without using bind
or =>
this is not bound in instance methods.
Take this example of a component
import React from "react";
export default class ES6Class extends React.Component {
constructor(props) {
super(props);
}
renderDetails() {
console.log("With regular function, this refers to: ", this);
this.showAlert();
}
sayHi() {
alert("oh hi!");
}
render() {
console.log("this in render?", this);
return <button onClick={this.renderDetails}>Click me!</button>;
}
}
Now, When I run this (https://codesandbox.io/embed/how-does-es6-classes-and-this-work-in-react-h4xm5), I get the following
For
console.log("this in render?", this);
I get
this in render?
ES6Class {props: Object, context: Object, refs: Object, updater: Object, _reactInternalFiber: FiberNode…}
But when I click on the button, I get
With regular function, this refers to: undefined
Now, I have the following questions,
- In the following code
<button onClick={this.renderDetails}>Click me!</button>;
What is this
refer to in this.renderDetails
? My 'guess'?
it refers to ES6Class
,
Why guess? because on button click, it executes the function renderDetails()
. Please correct me if I am wrong.
- Why
this
is undefined in
renderDetails() {
console.log("With regular function, this refers to: ", this);
this.showAlert();
}
When button
is clicked?
I am super confused. I even read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes, but could not understand this.
Please help me understand and point to official resources if possible. The code is available at
https://codesandbox.io/embed/how-does-es6-classes-and-this-work-in-react-h4xm5
THANK YOU
UPDATE 1
Thanks for the answers, I continue to fiddle with it. Next, I tried the following
let i = new ES6Class();
i.renderDetails();
let f = i.renderDetails;
f();
In this case, what I get is following
With regular function, this refers to:
ES6Class {props: undefined, context: undefined, refs: Object, updater: Object, constructor: Object}
With regular function, this refers to: undefined
Question: why is it undefined
and not Global
or Window
?