arrow function 的不同

preface

今天在推上看了一篇关于 arrow function 和 regular 函数的对比

函数中 this 指向问题 跟 函数的调用有关

总结了 下 arrow 函数中 不同如下

1. this 指向问题

无论 this值 在什么地方执行, 箭头函数中的 this 值 总是 等于 外部函数中的 this

bind, apply, call 不可应用于 箭头函数,并不能改变 this 值

2. this arguments 使用

箭头函数中 没有定义 arguments 关键字, 箭头函数中的 argumentsthis 值一样, 等于 外部函数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 指向是固定 到 类的实例上了

参考文档

文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值