JavaScript-ES6-function

JavaScript-ES6-function

這篇簡介JavaScript-ES6-function。

default parameter part I:

ES6 allow default parameter:

function log(x, y = ‘World’) {
console.log(x, y);
}

log(‘Hello’) // Hello World
log(‘Hello’, ‘China’) // Hello China
log(‘Hello’, ‘’) // Hello

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

const p = new Point();
p // { x: 0, y: 0 }

default parameter part II:

default parameter Cannot redeclare let or const:
function foo(x = 5) {
let x = 1; // error
const x = 2; // error
}

default parameter
function Cannot have same parameter name:
// non-error
function foo(x, x, y) {
// …
}

// error
function foo(x, x, y = 1) {
// …
}
// SyntaxError: Duplicate parameter name not allowed in this context

每次呼叫function時,default parameter都會重新計算 x + 1,不會使用上一次的default parameter

let x = 99;
function foo(p = x + 1) {
console.log(p);
}

foo() // 100

x = 100;
foo() // 101

default parameter combine ObjectDestructuration:

function foo({x, y = 5}) {
console.log(x, y);
}

foo({}) // undefined 5
foo({x: 1}) // 1 5
foo({x: 1, y: 2}) // 1 2
foo() // TypeError: Cannot read property ‘x’ of undefined