2021-05-11

Posted 前端世界升级打怪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-05-11相关的知识,希望对你有一定的参考价值。

ES6新特性分享(三)


一.箭头函数


ES6 允许使用「箭头」(=>)定义函数。

//声明一个函数
        // let fn = function(){

        // }
//箭头函数
        // let fn = (a,b) => {
        //     return a + b;
        // }


箭头函数的注意点:


1) 如果形参只有一个,则小括号可以省略

/**
*  省略小括号的情况
*/
let fn2 = num => {
 return num * 10;
};

2) 函数体如果只有一条语句,则花括号可以省略,函数的返回值为该条语句的执行结果
 

/**
* .省略花括号的情况
*/
let fn3 = score => score * 20;


3) 箭头函数 this 指向声明时所在作用域下 this 的值

/**
* this 指向声明时所在作用域中 this 的值
*/
let fn4 = () => {
 console.log(this);
let shuaige = {
 name: '奇奇',
 getName(){
 let fn5 = () => {
 console.log(this);
 }
 fn5();
 }
};


4) 箭头函数不能作为构造函数实例化

//运行看效果
 // let Person = (name, age) => {
        //     this.name = name;
        //     this.age = age;
        // }
        // let me = new Person('xiao',30);
        // console.log(me);


5) 不能使用 arguments

//运行看效果
// let fn = () => {
        //     console.log(arguments);
        // }
        // fn(1,2,3);

箭头函数常用来指定回调函数,因为他不会更改this的指向



二. rest 参数


ES6 引入 rest 参数,用于获取函数的实参,用来代替 arguments

/**
* 作用与 arguments 类似
*/
function add(...args){
 console.log(args);
}
add(1,2,3,4,5);
/**
* rest 参数必须是最后一个形参
*/
function minus(a,b,...args){
 console.log(a,b,args);
}
minus(100,1,2,3,4,5,19);

rest 参数非常适合不定个数参数函数的场景


结尾

继续加油。

以上是关于2021-05-11的主要内容,如果未能解决你的问题,请参考以下文章

2021-05-11

《安富莱嵌入式周报》第212期:2021.05.11--2021.05.17

2021-05-11

Makerdown学习 2021-05-11

2021-05-11

2021-05-11