ES6参数默认值

  • 在书写形参时,直接给形参赋值,附的值即为默认值
    这样一来,当调用函数时,如果没有给对应的参数赋值(给它的值是undefined),则会自动使用默认值。

举个栗子

function sum(a, b = 1, c = 2) {
    return a + b + c;
}

console.log(sum(10, undefined, undefined)) // 13
console.log(sum(11)) // 14
console.log(sum(1, undefined, 5)) // 7

[扩展]对arguments的影响

  • 只要给函数加上参数默认值,该函数会自动变量严格模式下的规则:arguments和形参脱离

举个例子

function test(a, b = 1) {
    console.log("arugments", arguments[0], arguments[1]); // 1 2
    console.log("a:", a, "b:", b); // 1 2
    a = 3; // 
    console.log("arugments", arguments[0], arguments[1]); // 此时a已经改变,argument却没有改变 1 2.
    console.log("a:", a, "b:", b); // 3 2
}

test(1, 2);

[扩展]留意暂时性死区

  • 形参和ES6中的let或const声明一样,具有作用域,并且根据参数的声明顺序,存在暂时性死区。
posted @ 2023-05-11 13:50  HuangBingQuan  阅读(36)  评论(0编辑  收藏  举报