es6箭头函数有什么优点

2022-03-07 17:26:00 IT技术网 互联网
浏览

es6箭头函数的优点:1、简明的语法,例“parameters => {statements;};”,应用起来更加的方便;2、能够隐式返回;3、更直观的作用域和this的绑定(不绑定this)。

本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

我们都知道,在 JavaScript 里定义函数有多种方式。最常见的是用function关键字:

// 函数声明
function sayHi(someone) {
  return `Hello, ${someone}!`;
}
// 函数表达式
const sayHi = function(someone) {
  return `Hello, ${someone}`;
}

上面的函数声明和函数表达式,我们姑且称之为常规函数。

还有就是 ES6 新增的箭头函数语法:

const sayHi = (someone) => {
  return `Hello, ${someone}!`;
}

相对于原先JS中的函数,ES6增长的箭头函数更加简洁,应用起来也更加的方便。

es6箭头函数的优点:

1、简明的语法

一个数组,把它变为原来的二倍之后输出。

删掉一个关键字,加上一个胖箭头;
没有参数加括号,一个参数可选择;
多个参数逗号分隔,

const numbers = [5,6,13,0,1,18,23];
//原函数
const double = numbers.map(function (number) {
    return number * 2;
})
console.log(double);
//输出结果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//箭头函数     去掉function, 添加胖箭头
const double2 = numbers.map((number) => {
    return number * 2;
})
console.log(double2);
//输出结果
//[ 10, 12, 26, 0, 2, 36, 46 ]
//若只有一个参数,小括号能够不写(选择)
const double3 = numbers.map(number => {
    return number * 2;
})
console.log(double3);
//如有多个参数,则括号必须写;若没有参数,()须要保留
const double4 = numbers.map((number,index) => {
    return `${index}:${number * 2}`;  //模板字符串
})
console.log(double4);

2、能够隐式返回

显示返回就是svg

const double3 = numbers.map(number => {
    return number * 2;  
    //return 返回内容;
})

箭头函数的隐式返回就是函数

当你想简单返回一些东西的时候,以下:去掉return和大括号,把返回内容移到一行,较为简洁;
const double3 = numbers.map(number => number * 2);

补充:箭头函数是匿名函数,若需调用,须赋值给一个变量,如上 double3。匿名函数在递归、解除函数绑定的时候颇有用。

3、更直观的作用域和this的绑定(不绑定this

一个对象,咱们原先在函数中是这么写的this

一个对象,咱们原先在函数中是这么写的

const Jelly = {
    name:'Jelly',
    hobbies:['Coding','Sleeping','Reading'],
    printHobbies:function () {
        this.hobbies.map(function (hobby) {
            console.log(`${this.name} loves ${hobby}`);
        })
    }
}
Jelly.printHobbies();
// undefined loves Coding
// undefined loves Sleeping
// undefined loves Reading

这说明 this.hobbies 的指向是正确的,this.name 的指向是不正确的;

当一个独立函数执行时,this 是指向window的

若是要正确指向,原先咱们的作法会是 设置变量替换spa

//中心代码
printHobbies:function () {
    var self = this; // 设置变量替换
    this.hobbies.map(function (hobby) {
        console.log(`${self.name} loves ${hobby}`);
    })
}
Jelly.printHobbies();
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading
在ES6箭头函数中,咱们这样写code
//中心代码
printHobbies:function () {
   this.hobbies.map((hobby)=>{
       console.log(`${this.name} loves ${hobby}`);
   })
}
// Jelly loves Coding
// Jelly loves Sleeping
// Jelly loves Reading

这是由于箭头函数中访问的this其实是继承自其父级做用域中的this,箭头函数自己的this是不存在的,这样就至关于箭头函数的this是在声明的时候就肯定了(词法做用域),this的指向并不会随方法的调用而改变。

【相关推荐:javascript视频教程、web前端】

以上就是es6箭头函数有什么优点的详细内容,更多请关注dnjidi.com其它相关文章!