ES6语法(二)

本篇介绍ES6的3个小知识点:箭头函数(与java中的lambda表达式相似) , 可变参数(与java中的可变参数相似),形参的默认值。

1.箭头函数 

特点:箭头函数与它的父层函数的this是一样的,因为箭头函数没有this;

          如果它的父层没有,会继续往上层找,直到找到最外层,window;

实例:

/**
 * (一)形参的情况
 */
//1. 没有形参
let fun1 = () => console.log("没有形参情况");
fun1();

//2.一个形参 刮号可以省略
let fun2 = info => console.log(`一个形参,${info}`);
fun2("测试啊");

//3.多个形参 必须要刮号
let fun3 = (name,age) => console.log(name,age);
fun3("liuqiang",23);

/**
 * (二)函数体的情况
 */
    //1.函数表达式 如果 let fun4 = (x,y) => {x + y} 是不会计算了 let fun4 = (x,y) => { return x + y}
let fun4 = (x,y) => x + y;
console.log(fun4(8,8));

//2.函数表达式(没有缩写)
let fun5 = (x,y) => {
    console.log(x,y);
    return x+y;
};
fun5(45,511);

console.log("------------------------");

/**
 * (三)箭头函数的this
 */
let obj = {
    name:"liuqiang",
    getName: () => console.log(this),
    animal: () => {
        let dog = () => console.log(this);
        dog();
    },
    food: function () {
        let apple = () => console.log(this);
        apple();
    }
};
obj.getName();//当前的this 是window 因为此函数的外层没有函数
obj.animal();//当前dog函数的this 是window 因为此函数的外层animal是箭头函数,没有this,继续向外找,没有函数
obj.food();//当前apple函数的this 是obj 因为此函数的外层food不是箭头函数,有this

2.可变参数(比较灵活,其实就是一个数组)

function test(...numbers) {
     numbers.forEach(function (item, index) {
        console.log(index+":"+item)
    })
}
//调用test函数一
test();
//调用test函数二
test(9,5,6);
//调用test函数一
test(9,5,6,25,5,44);


//三点运算符 自动遍历
let arr = [1,6];
let arr1 = [2,3,4,5];
arr = [1,...arr1,6];
console.log(arr);//结果:[1, 2, 3, 4, 5, 6]

3.形参的默认值(就是调用函数传递参数时,有些函数上的参数没有被传递的话,就采用函数上定义的默认值)

//设置形参的默认值为0
function Point(x = 0,y = 0) {
    this.x = x;
    this.y = y;
}
let point = new Point(22,24);
console.log(point);

//如果不设置形参的默认值,则x与y是undefined
let point1 = new Point();
console.log(point1);


猜你喜欢

转载自blog.csdn.net/qq_33429583/article/details/80341169