您现在的位置是:群英 > 开发技术 > web开发
ES6箭头函数适用于什么地方,使用要注意什么
Admin发表于 2022-09-13 17:05:23461 次浏览
在实际案例的操作过程中,我们可能会遇到“ES6箭头函数适用于什么地方,使用要注意什么”这样的问题,那么我们该如何处理和解决这样的情况呢?这篇小编就给大家总结了一些方法,具有一定的借鉴价值,希望对大家有所帮助,接下来就让小编带领大家一起了解看看吧。

简介

箭头函数表达式的语法比函数表达式更简洁,并且没有自己的this,arguments,super或new.target。箭头函数表达式更适用于那些本来需要匿名函数的地方,并且它不能用作构造函数。 ---- MDN

基础用法

参数表示

(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
//相当于:(param1, param2, …, paramN) =>{ return expression; }

// 当只有一个参数时,圆括号是可选的:
(singleParam) => { statements }
singleParam => { statements }

// 没有参数的函数应该写成一对圆括号。
() => { statements }

返回值表示

let add1 = (num1, num2) => {
  num1 + num2
};
let add2 = (num1, num2) => {
  return num1 + num2
};
let add3 = (num1, num2) => (num1 + num2);
let add4 = (num1, num2) => num1 + num2;

console.log(add1(2, 3));  // undefined
console.log(add2(2, 3)); // 5
console.log(add3(2, 3)); // 5
console.log(add4(2, 3)); // 5

进阶

//加括号的函数体返回对象字面量表达式:
let func = () => ({foo: 'bar'})
console.log(func()); // {foo: 'bar'}


//支持剩余参数和默认参数
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }

//同样支持参数列表解构
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6

this

最佳实践

  • 如果必须使用匿名函数,或者inline 回调函数,使用箭头函数。eslint: prefer-arrow-callback, arrow-spacing

why?语法更简洁,并且this更符合预期
如果函数逻辑相当复杂,应当使用命名函数

// bad[1, 2, 3].map(function (x) {
  const y = x + 1;
  return x * y;});// good[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;});
  • 如果函数体只有一条语句,且该语句不会产生副作用。使用简写方式,隐式返回;或者使用完整写法,显式return。
    eslint: arrow-parens, arrow-body-style
// bad
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map(number => `A string containing the ${number}.`);

// good
[1, 2, 3].map((number) => {
  const nextNumber = number + 1;
  return `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map((number, index) => ({
  [index]: number,
}));

// No implicit return with side effects
function foo(callback) {
  const val = callback();
  if (val === true) {
    // Do something if callback returns true
  }
}

let bool = false;

// bad
foo(() => bool = true);

// good
foo(() => {
  bool = true;
});
  • 当表达式占多行时,使用括号括起来增强可读性

why?函数开头和结束更明确

// bad['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  ));// good['get', 'post', 'put'].map(httpMethod => (
  Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  )));
  • 如果函数只有一个参数,省略括号,省略花括号。否则,一直使用完整写法,保持一致性。eslint: arrow-parens
// bad[1, 2, 3].map((x) => x * x);// good[1, 2, 3].map(x => x * x);// good[1, 2, 3].map(number => (
  `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!`));// bad[1, 2, 3].map(x => {
  const y = x + 1;
  return x * y;});// good[1, 2, 3].map((x) => {
  const y = x + 1;
  return x * y;});
  • 使用无歧义的=>语法,与<=,>=区分开。eslint: no-confusing-arrow
// badconst itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;// badconst itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;// goodconst itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);// goodconst itemHeight = (item) => {
  const { height, largeSize, smallSize } = item;
  return height > 256 ? largeSize : smallSize;

简单结论

  • 箭头函数不能用new来创建构造函数的实例,普通函数可以(因为箭头函数创建的时候程序不会为它创建construct方法,也就是没有构造能力,用完就丢掉了,不像普通函数重复利用,因此也不需要构造函数原型,也就是不会自动生成prototype属性)

  • 程序不会给箭头函数创建arguments对象

  • 普通函数中的this是动态的,而箭头函数中的this指向的是紧紧包裹箭头函数的那个对象(定义时决定的)

  • 箭头函数不能通过bind、call、apply来改变this的值,但依然可以调用这几个方法(只是this的值不受这几个方法控制)


通过以上内容的阐述,相信大家对“ES6箭头函数适用于什么地方,使用要注意什么”已经有了进一步的了解,更多相关的问题,欢迎关注群英网络或到群英官网咨询客服。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

标签: ES6
相关信息推荐
2022-10-09 18:15:37 
摘要:这篇文章主要介绍了如何利用 SpringBoot 在 ES 中实现类似连表的查询功能,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
2021-10-28 18:54:18 
摘要:本文我们主要了解PHP中date()函数的内容,那么date()函数能做什么呢?date() 函数功能是用于格式化时间,返回一个字符串。date()函数的应用还是比较多的,也是一个很基础的函数,所以要掌握date()函数的用法,那么date()函数怎样用呢?
2021-11-03 17:49:06 
摘要:这篇文章给大家分享的是PHP中的引用符&的内容。小编觉得挺实用的,因此分享给大家做个参考,对新手学习PHP有一定的帮助,文中示例代码介绍的非常详细,感兴趣的朋友接下来一起跟随小编看看吧。
云活动
推荐内容
热门关键词
热门信息
群英网络助力开启安全的云计算之旅
立即注册,领取新人大礼包
  • 联系我们
  • 24小时售后:4006784567
  • 24小时TEL :0668-2555666
  • 售前咨询TEL:400-678-4567

  • 官方微信

    官方微信
Copyright  ©  QY  Network  Company  Ltd. All  Rights  Reserved. 2003-2019  群英网络  版权所有   茂名市群英网络有限公司
增值电信经营许可证 : B1.B2-20140078   粤ICP备09006778号
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
微信公众号
返回顶部
返回顶部 返回顶部