ES6 了解之函数

箭头函数

基本用法

  • 箭头指向的是返回值
let a = () => 1;
let b = x => x;

let c = (x, y) => x+y;
// 或者 代码块部分多于一条语句 let c = (x, y) => { return x+y; }

let d = (x, y) => ({ id: x, name: y });
// 返回值为一个对象时, 需要() 包住该对象值. 或者 let d = (x, y) => { return {id: x, name: y} };

等同于

let a = function () {
    return 1;
}
let b = function (x) {
    return x;
}
let c = function (x, y) {
    return x+y;
}
let d = function (x, y) {
    return {
        id: x,
        name: y
    };
}

形参方式用法

[1, 2, 3].map(x => x + 1); // 返回结果 [2, 3, 4]

等同于

[1, 2, 3].map(function (x) {
    return x + 1;
});

和rest参数结合的用法

  • 以形参方式传值时, 默认从左到右依次传参, 其余的参数合为一个
场景一:

let demo = (...nums) => nums;

demo(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

场景二:

let demo = (num01, ...num02) => nums;

demo(1, 2, 3, 4, 5); // [1, [2, 3, 4, 5]]

延伸知识点: Rest参数

函数参数的默认值

常用写法

function demo(x, y) {
  y = y || 'HChiu';
  console.log(x, y);
}

正常:
demo('Hello')            // Hello HChiu
demo('Hello', 'Anuo')    // Hello Anuo
demo('Hello', 'false')   // Hello false
demo('Hello', true)      // Hello true

缺点: 当传参值为fasle或者空字符串时, 该值会被默认值取代.
demo('Hello', false)     // Hello HChiu
demo('Hello', '')        // Hello HChiu

ES6写法

场景一:

function demo(x, y = 'HChiu') {
   console.log(x, y);
}

demo('Hello')               // Hello HChiu
demo('Hello', false)        // Hello false
demo('Hello', '')           // Hello
demo('Hello', 'undefined')  // Hello undefined

demo('Hello', undefined)    // Hello HChiu


场景二:

function demo (x = 0, y = 0) {
    this.x = x;
    this.y = y;
}

let t = new demo(); // {x: 0, y: 0}

️注意:

  • 以形参的方式, 已经是默认的变量声明, 无需再重复声明同一个变量名, 报错 Uncaught SyntaxError: Unexpected identifier
  • 形参的声明, 同样也需要避免重复.

DEMO:

场景一:

function demo(x, x, y) {return x+x+y}

demo(1, 2, 3); // 7 , 前一个x, 会被后者覆盖

场景二:

function demo(x, x = 3, y) {
    return x+x+y;
}
demo(1, 2) // 不允许重复参数名, Uncaught SyntaxError: Duplicate parameter name not allowed in this context

场景三:

function demo(x) {
   let x;
}

demo(1); // Uncaught SyntaxError: Unexpected identifier

与解构赋值默认值的结合使用

function demo({x, y = 1}) {
  console.log(x, y);
}

demo({})             // undefined 1
demo({x: 2})         // 2 1
demo({x: 2, y: 2})   // 2 2
demo()               // TypeError: Cannot read property 'x' of undefined

延伸知识点: 解构赋值

posted @ 2017-11-30 14:23  chiuyer  阅读(123)  评论(0)    收藏  举报