Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ES6类中为什么需要绑定_Javascript_Reactjs - Fatal编程技术网

Javascript ES6类中为什么需要绑定

Javascript ES6类中为什么需要绑定,javascript,reactjs,Javascript,Reactjs,在新的React ES6类中,需要按如下所述绑定此: 例如: 对此的解释是因为这是默认行为,但是如果我创建一个ES6类,然后创建它的一个新实例,this将被绑定 import React from 'React' class Test extends React.Component { constructor() { super() } foo () { console.log('bar') } hello() { t

在新的React ES6类
中,需要按如下所述绑定此
: 例如:

对此的解释是因为这是默认行为,但是如果我创建一个ES6类,然后创建它的一个新实例,
this
将被绑定

import React from 'React'

class Test extends React.Component {
    constructor() {
      super()
    }
    foo () {
      console.log('bar')
    }
    hello() {
      this.foo()
    }
}

var test = new Test()
test.hello()
// > bar

为什么在React-then中需要绑定?

您需要为方法设置
this
,例如,如果您需要将函数引用传递给事件处理程序,但不需要为每个方法设置
this

class Counter extends React.Component {
  constructor() {
    super();
    this.tick = this.tick.bind(this);
  }

  tick() {
    // this refers to Counter
  }

  fn() {
    // this refers to Counter
  }

  withoutBind() {
    // this will be undefined or window it depends if you use "strict mode" or not
  }

  render() {

    this.fn(); // this inside this method refers to Counter

    // but if you will do like this
    const fn = this.fn;
    fn(); // this will refer to global scope


    return <div>
      <button onClick={this.tick}>1</button>
      <button onClick={this.withoutBind}>2</button>
    </div>;
  }
}
类计数器扩展React.Component{
构造函数(){
超级();
this.tick=this.tick.bind(this);
}
勾选(){
//这是指计数器
}
fn(){
//这是指计数器
}
不绑定(){
//这将是未定义的或窗口,这取决于您是否使用“严格模式”
}
render(){
this.fn();//此方法中的此引用计数器
//但是如果你愿意这样做
const fn=this.fn;
fn();//这将引用全局范围
返回
1.
2.
;
}
}

ES6中的类是函数。当你实例化一个类时,你会得到一个对象。类中的所有方法,如果在它们内部使用
this
,则它引用拥有该方法的对象

但是,当您提取该方法时会感到困惑,因为上下文会发生变化。示例:

let foo = Counter()
foo.tick()
如果调用
foo.tick()
,则该
属于对象foo。酷

但请注意:

tickFunc = foo.tick()
tickFunc()
您将函数从原始对象中分离,现在函数调用发生在
this
内部
tickFunc()
引用全局对象的位置


那么,为什么需要在React中绑定方法呢?之所以这样做,是因为在大多数情况下,我们将方法引用传递给事件处理程序或作为组件的道具。当您传递方法的引用时,它们将成为分离的函数,并且它们的上下文将发生更改。要解决这个问题,您可以在构造函数中使用
bind()

这是一个非常好的资源,有助于真正理解
这个
和函数上下文:
tickFunc = foo.tick()
tickFunc()