3 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
JavaScript不支持方法重載(如Java或類似方法),您的第三個(gè)函數(shù)將覆蓋之前的聲明。
而是通過(guò)argumentsobject支持變量參數(shù)。你可以做
function somefunction(a, b) {
if (arguments.length == 0) { // a, b are undefined
// 1st body
} else if (arguments.length == 1) { // b is undefined
// 2nd body
} else if (arguments.length == 2) { // both have values
// 3rd body
} // else throw new SyntaxError?
}
你也可以只檢查typeof a == "undefined"等,這將允許呼叫somefunction(undefined),其中arguments.length為1。這可能允許使用各種參數(shù)進(jìn)行輕松調(diào)用,例如,當(dāng)您有可能為空的變量時(shí)。

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
JS將傳遞undefined未提供的任何參數(shù)。如果您想要類似重載的操作,則需要執(zhí)行類似于以下代碼的操作:
function someFunction(a, b) {
if (typeof a === 'undefined') {
// Do the 0-parameter logic
} else if (typeof b === 'undefined') {
// Do the 1-parameter logic
} else {
// Do the 2-parameter logic
}
}

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
您只是在somefunction每個(gè)新聲明中擦除變量。
這相當(dāng)于
window.somefunction = function(...
window.somefunction = function(...
window.somefunction = function(...
Javascript不提供方法重載。
正確的方法是:
定義第三個(gè)功能并測(cè)試定義了哪些參數(shù)
只傳遞一個(gè)包含參數(shù)的對(duì)象(這并沒(méi)有什么不同,但更干凈)
添加回答
舉報(bào)