this指向
普通函数
- 如果这个函数没有被它上一级对象所调用,那么this默认指向window。在严格模式中this指向undefined
- 如果这个函数被它上一级的对象所调用,那么this指向他它上一级的对象
特殊情况:
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn; // 虽然fn被b对象所引用,但是并没有执行
j() // 这里相当于window.j(),所以指向window箭头函数
箭头函数本身没有this,所以指向外层代码块的this,也就是父执行函数上下文的this
定义函数
使用箭头函数
import React, { PureComponent } from 'react';
// 第一种
class Add extends PureComponent {
constructor(props) {
super(props);
}
render() {
return <div onClick={this.onRequest}>请求</div>;
}
onRequest = (arg1, arg2) => {
console.log('this', this); // Add{}
}
}
// 第二种
render() {
return (
<div onClick={(e) => this.onRequest(arg1, arg2, e)}>请求哦</div>
);
}
onRequest(arg1, arg2, e) {
console.log('this', this); // Add{}
}第一种写法需要Babel或者你的应用构建工具的支持
第二种情况,在render中使用箭头函数,那么在每次render时都会去创建一个新的函数,对性能不好。
用bind()绑定
import React, { PureComponent } from 'react';
// 第一种
class Add extends PureComponent {
constructor(props) {
super(props);
this.onRequest = this.onRequest.bind(this, arg1, arg2);
}
render() {
return <div onClick={this.onRequest}>请求</div>;
}
onRequest (arg1, arg2) {
console.log('this', this); // Add{}
}
}
// 第二种
class Add extends PureComponent {
constructor(props) {
super(props);
}
render() {
return <div onClick={this.onRequest.bind(this, arg1, arg2)}>请求</div>;
}
onRequest (arg1, arg2) {
console.log('this', this); // Add{}
}
}在constructor里绑定的好处是只需要绑定一次,避免每次渲染时都要重新绑定,而且在别处复用时也不用重新绑定。第二种情况需要每次都绑定。
总结
- 如果你的环境支持箭头函数,那么鼓励使用
- 如果有需要,可以在render使用箭头函数,但是为了性能考虑尽量避免