es6預設引數
阿新 • • 發佈:2019-03-19
es5 要實現預設引數,一般是
在大括號裡 寫,
function calc(x, y) {
x = x || 0;
y = y || 0;
// to do with x, y
// return x/y
}
es6後,直接用語言本身來處理, 寫在小括號裡
function calc(x=0, y=0) {
console.log(x,y)
}
預設引數可以不是一個值型別,它可以是一個函式呼叫
function throwIf() {
throw new Error('少傳了引數');
}
function ajax(url=throwIf(), async=true, success) {
return url;
}
ajax(); // 沒有傳url,則使用預設引數 throwIf() 返回Error: 少傳了引數
=============================================================
定義了預設引數,函式的length屬性會減少,即有預設引數不包含在length的計算當中
function calc(x=0, y=0) { console.log(x, y) } function ajax(url, async=true, dataType="JSON") { console.log(url, async, dataType) } console.log(calc.length); // 0 x,y 2個都有預設引數,不參與計算 console.log(ajax.length); // 1
function.length和 arguments的區別:
function.length:接收到函式體外的引數計算長度
arguments:接收到函式體內的引數計算長度