0

Per my understanding, arrow function should have same same scope with the context where it was created in. Like below one return:" This is the box number green big ", which I understand.

let box6={
    color:'green',
    position:1,
    font:'big',
    clickMe:function(){
    return ()=>{
    let str='This is the box number '+this.color+' '+ this.font;
    console.log(str)
    }  }
    }

but in React Class, the handleClick arrow function is defined in class LoggingButton, it suppose to have same scope with it, but in the console, it returns: this is LoggingButton, I thought it should return global scope or whatever scope one level higher than LoggingButton. why is this happening? Thank you very much!!!

class LoggingButton extends Component {
  handleClick=()=>{
    console.log('this is :', this)
  }
  render() {
    return (
      <div className="App">
       <button onClick={this.handleClick}>Click Me</button>
      </div>
    );
  }
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
MARS
  • 33
  • 6
  • You might be confused by the `handleClick = …` syntax. That's actually happening in the constructor. – Bergi Dec 17 '18 at 21:32
  • If `handleClick` was a regular function the scope of `this` would be within `handleClick`. "One level higher" is `LoggingButton`. – wdm Dec 17 '18 at 22:01

1 Answers1

-4

It is pretty simple.

()=>{} is the same as function(){}.bind(this). And this in your case is LoggingButton.

Please let me know if that helps.