基于通过的参数重写Javascript函数 [英] Override Javascript Function Based on Passed Parameters

查看:95
本文介绍了基于通过的参数重写Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据传入的参数数量覆盖函数?例如:

 函数abc(name){
document.write('My name is'+ name);
}

函数abc(name,friend){
document.write('我的名字是'+ name +',我最好的朋友''的名字是'+朋友);





$ b因此在HTML中,如果我只是调用abc(george),它会使用第一个版本的函数,但如果我调用abc(george,john),它会使用第二个版本。



可能有其他方法可以完成我使用的示例,但我只是想知道在JavaScript中这个概念是否合理。

解决方案

JavaScript不支持函数重载。



然而,您可以:

  if(typeof friend ===undefined ){
//做某事
}其他$ {
//做别的事
}


Is it possible to override a function based on the number of parameters that you are passing into it? For instance:

function abc(name) {
    document.write ('My name is' + name);
}

function abc(name,friend) {
    document.write ('My name is' + name + 'and my best friend\'s name is' + friend);
}

So in the HTML if I just called abc(george) it would use the first version of the function, but if I called abc(george,john) it would use the second version.

There may be other ways to accomplish the example I used, but I'm just wondering if the concept is sound in javascript.

解决方案

JavaScript does not support function overloading.

You can, however:

if (typeof friend === "undefined") {
    // do something
} else {
    // do something else
}

这篇关于基于通过的参数重写Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆