【问题标题】:this scope in Arrow Function in Javascript [duplicate]Javascript中箭头函数中的这个范围[重复]
【发布时间】:2019-05-18 06:54:18
【问题描述】:

根据我的理解,箭头函数应该与创建它的上下文具有相同的范围。 就像下面一个返回:“这是绿色大号的框号”,我明白了。

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)
    }  }
    }

但是在 React 类中,handleClick 箭头函数是在类 LoggingButton 中定义的,它假设与它具有相同的作用域,但在控制台中,它返回:这是 LoggingButton,我认为它应该返回全局作用域或任何作用域级别高于 LoggingButton。 为什么会这样? 非常感谢!!!

class LoggingButton extends Component {
  handleClick=()=>{
    console.log('this is :', this)
  }
  render() {
    return (
      <div className="App">
       <button onClick={this.handleClick}>Click Me</button>
      </div>
    );
  }
}

【问题讨论】:

  • 您可能对handleClick = … 语法感到困惑。这实际上发生在构造函数中。
  • 如果handleClick 是常规函数,则this 的范围将在handleClick 内。 “上一级”是LoggingButton

标签: javascript reactjs class scope this


【解决方案1】:

这很简单。

()=&gt;{}function(){}.bind(this) 相同。你的情况是LoggingButton

如果有帮助,请告诉我。

【讨论】:

猜你喜欢
  • 2015-05-02
  • 2018-07-02
  • 2016-01-08
  • 2020-03-07
  • 2023-03-12
  • 1970-01-01
  • 2020-11-08
  • 2016-09-30
相关资源
最近更新 更多