While learning JS and React I've come across confusing differences in tutorials.
I'll split the questions below with examples. I understand bind for regular functions and this context, it's just arrow functions and how I've seen them used/declared that's confusing.
Please don't just refer to duplicates as I've found conflicting answers in tutorials which have confused me, so looking for the source of truth to understand in a simple way. Answers related to the questions and examples below would help better.
1 - I've seen examples where a tutorial says the value of 'this' would be window as the arrow function inherits from the global/window scope but I've also seen tutorials where they say it will inherit this from the class context - which is correct? if you could please explain.
class MyClass {
value = 'Hello World!'
clickHandler = () => { console.log(this.value) };
}
2 - I have 2 parts to this question - i - Why is the syntax clickHandler = () => rather than clickHandler () =>
I ask this because I read class methods can be defined with 'functionName () {}' so why do arrow functions treat the method name as a variable?
ii - What is the value of this in the below code? same as question 1 I guess, does this refer to the window object or the class?
class Foo extends React.Component {
constructor() {
}
clickhandler = () => {
console.log("you clicked me!!")
}
render() {
return(
<div>
<button onClick={this.clickhandler}> // => CALLBACK
3 - Here I see the event handler is an inline function, but it looks like it gets invoked because of the () at the end, sometimes as in the follow on snippet, you can see that just the function name is given without the parentheses, shouldn't they be there also?
class MyComponent extends React.Component {
showValue() {
console.log(this.props.value);
}
render() {
return (
<button onClick={() => this.showValue()}>Do Something</button>
);
}
}
-------------------------------------------
showValue() {
console.log(this.props.value);
}
render() {
return (
<button onClick={this.showValue}>Do Something</button>
);
}