为什么该事件处理程序不在范围内时可以访问类属性?

时间:2019-07-21 03:34:41

标签: javascript reactjs class ecmascript-6 scope

此摘录来自一篇中篇文章。为什么第一个<button onClick={this.handleClick1()}>click 1</button>可以访问该类中的实际属性?

/**
 * Can you explain the differences between all those ways
 * of passing function to a component?
 *
 * What happens when you click each of the buttons?
 */
/**
 * Can you explain the differences between all those ways
 * of passing function to a component?
 *
 * What happens when you click each of the buttons?
 */
class App extends React.Component {

  constructor() {
    super(); 
    this.name = 'MyComponent';

    this.handleClick2 = this.handleClick1.bind(this);
  }

  handleClick1() {
    alert(this.name);
  }

  handleClick3 = () => alert(this.name);
render() {
    return (
      <div>
        <button onClick={this.handleClick1()}>click 1</button>
        <button onClick={this.handleClick1}>click 2</button>
        <button onClick={this.handleClick2}>click 3</button>
        <button onClick={this.handleClick3}>click 4</button>
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

  

为什么第一个<button onClick={this.handleClick1()}>click 1</button>可以访问该类中的实际属性?

this.handleClick1()随即在此位置调​​用该函数,即稍后触发该事件时handleClick1返回undefined,因此实际上没有绑定任何事件处理程序。

并且由于该函数称为对象属性(x.y()),因此onClick1自己的this值设置为.之前的值(也称为{{ 1}})。

答案 1 :(得分:0)

因为它与this绑定

this.handleClick2 = this.handleClick1.bind(this);

Function.prototype.bind