Maison > interface Web > js tutoriel > le corps du texte

JavaScript中实现函数重载和参数默认值

高洛峰
Libérer: 2016-11-26 14:08:54
original
1603 Les gens l'ont consulté

参数默认值是指在调用函数时,若省略了某个实参,函数会自动为该参数分配一个默认值,使得函数调用的方便性和灵活性大大提高。

举个例子,比如PHP中的字符串截取函数substr(string,start,length),当不指定length时,函数将默认截取字符串中start位置到字符串结束,而如果指定了length,则截取从start位置开始的以length为长度的字符串,所以如果调用的是substr('http://www.hualai.net.cn',11,6),则返回的是hualai;如果省略掉最后一个参数,substr('http://www.hualai.net.cn',11),则返回hualai.net.cn。

再比如jQuery框架中,$(selector).html()方法是获取该元素内的HTML代码,而$(selector).html(content)则是设置该元素内的HTML。我们知道,在C语言中,我们可以通过如下形式来为函数参数设置默认值:


void foo(int a, int b = 1, bool c = false);  



在Java中,则可以通过函数重载来设置函数参数默认值:

public void foo(int a){  
    foo(a, 1);  
}  
public void foo(int a, int b){  
    foo(a, b, false);  
}  
public void foo(int a, int b, bool c){  
    //函数内容  
}  




而在JavaScript中,如何像jQuery那样设置函数参数默认值呢?JavaScript中并没有像C语言中定义函数时直接在参数后面赋值的方法,也没有像Java里那样的函数重载,但我们可以通过JavaScript方法中的一个arguments只读变量数组来实现,具体如下:

function foo(){  
    var a = arguments[0] ? arguments[0] : 1;  
    var b = arguments[1] ? arguments[1] : false;  
    //函数内容  
}  



以上是通过判断参数是否存在,若不存在则将默认值附给变量,而我们可以通过判断参数的类型来实现重载:

function foo(){  
    if(typeof arguments[0] == 'string')   
        alert('参数类型为字符串');   
    else if(typeof arguments[0] == 'number')   
        alert('参数类型为数值');   
}  


或者

function foo(){  
    if(arguments[0].constructor == String)   
        alert('参数类型为字符串');   
    else if(arguments[0].constructor == Number)   
        alert('参数类型为数值');   
}  


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!