this指向以及react中绑定this

JavaScript函数中的this
  • 我们都知道JavaScript函数中的this不是在函数声明的时候定义的,而是函数调用(即运行)的时候定义的,this对象是运行时基于函数的执行环境(也就是上下文)绑定的。
var student = {
     func:function(){
          console.log(this)
     }
}

student.func();  // 打印了student对象,因为此时this指向student对象
var studentFunc = student.func;
studentFunc();  // 打印了window,因为此时是window调用的,this指向window
es6中class的this的指向
class Logger{
    printName(){
          this.print(`Hello ${name}`);
    }
    print(text){
        console.log(text);
    }
}

const logger = new Logger();
const {printName} = logger;
printName(); 

上述代码中,printName方法中的this默认指向Logger类的实例。但是如果将这个方法提取出来单独使用,this指向该方法运行时所在的环境(由于class内部是严格模式,所以this实际指向的是undefined),从而导致找不到print方法而报错。
一个比较简单的解决方法是,在构造方法中绑定this,这样就不会找不到print方法了。

constructor() {
      this.printName = this.printName.bind(this)
}

另一种解决方法是使用箭头函数。箭头函数内部的this总是指向定义时所在的对象。

React中绑定this
class LikeButton extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
  }
  render() {
    return (
      <div onClick={this.handleClick}>
      </div>
    );
  }
}
  • 在原来React.createClass中,handleClick() 在onClick事件触发的时候,会自动绑定到LikeButton实例上
  • 在ES6的class的写法中,Facebook取消了自动绑定。因为render多次调用每次都要bind会影响性能,对此我们有如下几种解决方案

使用bind()绑定的方法

\color{#f00}{直接bind * this型/constructor手动bind型}

  • 传参:
    第一个参数指向this,第二个参数开始才是事件函数接收到的参数
    事件对象e以及更多的参数将会被隐式的进行传递
    在类组件中定义的监听函数,事件对象e要排在所传递参数的后面
class Hello extends React.Component{
    constructor(){
        super()
        this.state = {
            content:true
        }
        this.change = this.change.bind(this,this.state.content) // 1.可以在constructor中绑定this
    }
    
    change(obj,e){ // 事件对象e被隐式传递并排在所传递参数的后面
      
    }

    render(){
        return (
            <div>
                <button onClick={this.change}>    {/*2.也可在具体使用该函数的时候绑定this.change.bind(this,this.state.content)*/}
                    点击
                </button>
            </div>
        )
    }
}

使用属性初始化器语法(还处于实验阶段)

class LoggingButton extends React.Component {
  // 这个语法确保了 `this` 绑定在  handleClick 中
  // 这里只是一个测试
  handleClick = () => {   // 传参的写法 andleClick = (params)
    console.log('this is:', this);
  }
 
  render() {
    return (
      <button onClick={this.handleClick}>   {/*传参的写法:onClick={this.handleClick(params)}*/}
        Click me
      </button>
    );
  }


}

在回调函数中使用箭头函数

  • 传参时,事件对象e必须进行显示的传递
  • 将函数的this绑定到其定义时所在的上下文
class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>  {/* 事件对象e必须进行显示的传递 */}
        Click me
      </button>
    );
  }
}
  • 弊端:每次LoggingButton渲染的时候都会创建一个\color{#FF0000}{不同}的回调函数。如果这个回调函数作为一个属性值传入低阶组件,这些组件可能会进行额外的渲染。所以建议在\color{#FF0000}{构造函数中绑定}或使用\color{#FF0000}{属性初始化器}语法来避免这类性能问题。

为什么使用bind而不是call和apply

  • 因为call和apply,都是立即就调用了对应的函数,而bind是返回一个函数,在调用的时候执行,传参方式跟call一样。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容