preface
今天在推上看了一篇关于 arrow function 和 regular 函数的对比
函数中 this 指向问题 跟 函数的调用有关
总结了 下 arrow 函数中 不同如下
1. this 指向问题
无论 this值 在什么地方执行, 箭头函数中的 this
值 总是 等于 外部函数中的 this
值
bind, apply, call
不可应用于 箭头函数,并不能改变 this 值
2. this arguments 使用
箭头函数中 没有定义 arguments
关键字, 箭头函数中的 arguments
同 this
值一样, 等于 外部函数的 arguments
function myRegularFunction() {
const myArrowFunction = () => {
console.log(arguments);
}
myArrowFunction('c', 'd');
}
myRegularFunction('a', 'b'); // logs { 0: 'a', 1: 'b' }
但是我们可以通过 the rest parameters
方式 去访问 箭头函数的所有参数
function myRegularFunction() {
const myArrowFunction = (...args) => {
console.log(args);
}
myArrowFunction('c', 'd');
}
myRegularFunction('a', 'b'); // logs { 0: 'c', 1: 'd' }
3. return 语句
隐式 return 语句
箭头函数中 只包含一个表达式的时候, 我们可以隐式 返回 这个表达式的值
const increment = (num) => num + 1;
increment(41); // => 42
当返回 一个 Object 的时候,我们可以如下操作:
const increment = (num) => ({ result: num + 1});
increment(41); // => {result: 42}
4. 在类中的使用
类中箭头函数中的 this
从词法上 是绑定到 类的实例上了
class Hero {
constructor(heroName, herAge) {
this.heroName = heroName;
this.heroAge = heroAge;
}
logName = () => {
console.log(this.heroName);
}
logAge() {
console.log(this.heroAge)
}
}
const batman = new Hero('Batman');
类的方法使用 普通声明 和 箭头函数 两种方式在 方法调用的时候没有不同, 但是 箭头函数中的this 指向是固定 到 类的实例上了