我们知道箭头函数没有自己的this,箭头函数的this取决于箭头函数在哪儿定义,而非箭头函数执行的上下文环境。
总之,箭头函数与普通函数的其他重要区别:
- 对this 的关联:函数内置 this 的值,取决于箭头函数在哪儿定义,而非箭头函数执行的上下文环境
- this 不可变:.call()/.apply()/.bind()无法改变箭头函数中this的指向
- new不可用:不能作为构造函数:不能使用
new来调用 - 没有arguments对象:没有自己的
super、arguments和new.target绑定 - 没有原型对象 prototype
- 不可以使用yield命令,因此箭头函数不能用字Generator函数中
const obj = {a: function() {console.log(this);},b: () => {console.log(this);}};obj.a(); //输出objobj.b(); //输出window
箭头函数 优于 普通函数
什么时候箭头函数更好?
比如react的时候,我们使用箭头函数,就不需要手动绑定this了
class Toggle extends React.Component {constructor(props) {super(props);this.state = {isToggleOn: true};// 为了在回调中使用 `this`,这个绑定是必不可少的// this.handleClick = this.handleClick.bind(this);}handleClick() {this.setState(state => ({isToggleOn: !state.isToggleOn}));}render() {return (<button onClick={() => {// console.log(this); # 箭头函数让this指向了 toggle实例this.handleClick();}}># 第二种手动bind的写法<button onClick={this.hanleClick}>{this.state.isToggleOn ? 'ON' : 'OFF'}</button>);}}
比如函数式编程的时候, 代码清晰,一点也不拖泥带水
# 柯里化
const addCurry = function(a){
return function(b){
return function(c){
return a+b+c;
}
}
}
const addCurry = a => b => c => a + b + c;
调用
addCurry(10)(5)(3) = 18
普通函数 优于 箭头函数
比如vue的时候,必须要function而不是箭头函数
1、与原型方法、对象方法、构造函数有关
# vue
<template>
<div id="app">
<button v-on:click="getData">点击</button>
</div>
</template>
<script>
export default {
data() {
return {
name: "hello",
};
},
methods: {
getData() { # getData必须是function,箭头函数 this 则会是undefined
console.log(this.name) // this指向当前vue实例
this.$nextTick(function () { # $nextTick里的回调,写箭头函数 和 普通函数都可以
// dom更新了 # this都是指向的 当前component实例
// this.doSomethingElse();
});
}
}
};
</script>
2、点击事件回调
const button = document.getElementById('myButton');
button.addEventListener('click', () => { # 此时使用普通函数 this指向按钮明显更方便
console.log(this === window); // => true
this.innerHTML = 'Clicked button';
});
