箭头函数和this的区别

箭头函数和this到底有啥区别?

箭头函数this的定义:箭头函数中的this是在定义函数的时候绑定,而不是在执行函数的时候绑定。

换一种说法

管在什么情况下,箭头函数的this跟外层function的this一致,外层function的this指向谁,箭头函数的this就指向谁,如果外层不是function则指向window。

1
2
3
4
5
6
7
8
9
var x=11;
var obj={
x:22,
say:function(){
console.log(this.x)
}
}
obj.say();
//console.log输出的是22

This必将指向内层function

1
2
3
4
5
6
7
8
9
var x=11;
var obj={
x:22,
say:()=>{
console.log(this.x);
}
}
obj.say();
//输出的值为11

=>必将指向外层function,如果外层不是function则指向window。

以一个React组件为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Square extends React.Component {
// 我们用 state 来实现所谓“记忆”的功能。
// constructor函数会初始化this.state
// this.state 中存储当前每个方格(Square)的值,并且在每次方格被点击的时候改变这个值。
constructor(props) {
super(props);
this.state = {
value: null,
};
}
render() {
return (
// Square组件渲染了一个单独的<button>
// 在 Square 组件 render 方法中的 onClick 事件监听函数中调用 this.setState,
// 我们就可以在每次 <button> 被点击的时候通知 React 去重新渲染 Square 组件。
<button
className="square"
onClick={() => {this.setState({value: 'X'})}}
// onClick={function() {this.setState({value: 'X'})}} // 用这种方法声明,就会报 TypeError: Cannot read property 'setState' of undefined 的错误。
>
{/* 添加数字绑定 */}
{this.state.value}
</button>
);
}
}

用这种方法声明,就会报 TypeError: Cannot read property 'setState' of undefined 的错误。因为 setState() 方法是Square类的方法。

1
onClick={function() {this.setState({value: 'X'})}}

而用下面这种方法,就不会报错,因为=>必将指向外层function,也就是Square类的方法,也就是Square.setState()。

1
onClick={() => {this.setState({value: 'X'})}}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!