function log(x, y = 'World') {
console.log(x, y);
}
log('Hello');
/* Hello World */
log('Hello', 'China');
/* Hello China */
log('Hello', '');
/* Hello */
function week({ x, y = 5 }) {
console.log(x, y);
}
week({});
/* undefined 5 */
week({x: 1});
/* 1 5 */
week({x: 1, y: 2});
/* 1 2 */
week();
/* TypeError: Cannot read property 'x' of undefined */
function week({x, y = 5} = {}) {
console.log(x, y);
}
week();
/* undefined 5 */
参数变量已经默认声明, 不能用let或const再次声明
function week(x = 5) {
let x = 1;
const x = 2;
}
/* SyntaxError: Identifier 'x' has already been declared */
函数不能有同名参数
function week(x, x, y = 1) {
/* ... */
}
/* SyntaxError: Duplicate parameter name not allowed in this context */
参数默认值是惰性求值
let x = 99;
function week(p = x + 1) {
console.log(p);
}
week();
/* 100 */
x = 100;
week();
/* 101 */
参数默认值一般用于尾部
length属性 - 返回没有指定默认值的参数个数
(function (a) {}).length;
/* 1 */
(function (a = 5) {}).length;
/* 0 */
(function (a, b, c = 5) {}).length;
/* 2 */
(function (a = 0, b, c) {}).length;
/* 0 */
(function (a, b = 1, c) {}).length;
/* 1 */
(function(...args) {}).length;
/* 0 */
设置了参数的默认值, 参数会形成一个单独的作用域
var x = 1;
function f(x, y = x) {
console.log(y);
}
f(2);
/* 2 */
let x = 1;
function f(y = x) {
let x = 2;
console.log(y);
}
f();
/* 1 */
function month(func = () => week) {
let week = 'inner';
console.log(func());
}
month();
/* ReferenceError: week is not defined */
var x = 1;
function week(x, y = function() { x = 2; }) {
var x = 3;
y();
console.log(x);
}
week();
/* 3 */
x;
/* 1 */
function throwIfMissing() {
throw new Error('Missing parameter');
}
function week(mustBeProvided = throwIfMissing()) {
return mustBeProvided;
}
week();
/* Error: Missing parameter */
```