JS支持兩個具有相同名稱和不同參數的函數嗎?JS和函數參數的幫助
function f1(a, b)
{
// a and b are numbers
}
function f1(a, b, c)
{
// a is a string
//b and c are numbers
}
我可以使用那些JS功能的IE7,FF,Opera沒有問題嗎?
JS支持兩個具有相同名稱和不同參數的函數嗎?JS和函數參數的幫助
function f1(a, b)
{
// a and b are numbers
}
function f1(a, b, c)
{
// a is a string
//b and c are numbers
}
我可以使用那些JS功能的IE7,FF,Opera沒有問題嗎?
JavaScript不支持,你會在其他語言方法重載叫什麼,但也有多種解決方法,就像使用arguments
對象,檢查與多少個參數的函數被調用:
function f1(a, b, c) {
if (arguments.length == 2) {
// f1 called with two arguments
} else if (arguments.length == 3) {
// f1 called with three arguments
}
}
另外,你可以輸入檢查你的論點,對於數字和字符串元安全使用typeof
操作:
function f1(a, b, c) {
if (typeof a == 'number' && typeof b == 'number') {
// a and b are numbers
} else if (typeof a == 'string' && typeof b == 'number' &&
typeof c == 'number') {
// a is a string, b and c are numbers
}
}
而且還有像一個下面的文章中,即利用更先進的技術一些JavaScript語言功能,如關閉,功能應用等,以模仿方法重載:
不,你不能在JS中使用函數重載。
但是,您可以用3個參數聲明版本,然後檢查第三個參數=== undefined
,並在此基礎上提供差異化的行爲。
不,這不起作用,只有第二個函數會在你的頁面上定義。 Here的來源。
不,你不能這樣做......除非你確定只有你的最後一個定義。
JavaScript只使用最後定義的函數。
http://weblogs.asp.net/jgalloway/archive/2005/10/02/426345.asp X
您將需要實現的功能裏面你自己的邏輯來確定被傳遞哪些參數。
你也可以使用instanceof,基本多態的例子。
首先創建一個超類(球)
// superclass
function Ball() {
this.play = function() {
alert("Ball throw");
};
}
現在對於某些子類(種球)
// subclass
function Basketball() {
this.play = function() {
alert("basketball throw");
};
}
// subclass
function Soccerball() {
this.play = function() {
alert("soccer ball kick/throw");
console.debug("here");
};
}
// subclass
function Baseball() {
this.play = function() {
alert("strike 3 you're out");
console.debug("here");
};
}
給他們球的功能,又名通過原型設置其超
// set subclass functionality
Basketball.prototype = new Ball();
Soccerball.prototype = new Ball();
Baseball.prototype = new Ball();
某些多態性(創建一串球並與它們一起玩,但玩基於o n型)
var bunchOfBalls = [new Baseball(), new Soccerball(), new Basketball()];
for (var i = 0; i < bunchOfBalls.length; i++) {
bunchOfBalls[i].play();
}
現在寫一個函數,一個球,但只希望爲特定類型的球的工作(模擬函數重載,更多或更少)
//overloading dependent upon type
function BasketbalOrBaseballOnlyPlay(aBall) {
if (aBall instanceof Basketball) {
//special basketball function
}
if (aBall instanceof Baseball) {
//special baseball function
}
}
如果aBall是籃球所以aBall = new Basketball();
然後aBall instanceof Basketball
將返回true爲籃球和虛假的棒球,但真正的球。
所以aBall instanceof Ball
將返回true,因爲籃球是球。
在調用者傳遞一個第三個參數,但它的價值是不確定* *本次測試將失敗的事件。如果函數測試** arguments.length **,可能會更好。 – NVRAM 2010-02-02 22:59:14
如果調用者使用'undefined'作爲第三個參數,我會用它來表示他們希望這個函數被視爲只有兩個被傳入。我真的沒有看到任何其他合法的目的傳遞在'undefined'中。 – 2010-02-02 23:05:38