Javascript中的方法重载 [英] Method overloading in Javascript

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

问题描述

我在我的Javascript代码中使用如下方法重载。

I use method overloading as below in my Javascript code.

function somefunction()
{
    //1st function
}

function somefunction(a)
{
   //2nd function
}

function somefunction(a,b)
{
   //3rd function
}

somefunction(); // function call goes here

我不明白的是,如果我调用 somefunction() javascript应该调用 1st函数,但问题是javascript实际上调用了第3个函数。这是为什么?如何调用第1和第2功能?这是什么原因?有没有一种在Javascript中实现方法重载的正确方法?什么是行业标准?

What I don't understand is if I call the somefunction() javascript should call the 1st function but the problem is javascript actually calls the 3rd function. Why is that? How can I call the 1st and 2nd function ? What is the reason for this? Is there a proper way to implement method overloading in Javascript? What's the industry standard?

推荐答案

JavaScript不支持方法重载(如Java或类似),您的第三个函数会覆盖以前的声明。

JavaScript does not support method overloading (as in Java or similiar), your third function overwrites the previous declarations.

相反,它通过 arguments object 。你可以做

Instead, it supports variable arguments via the arguments object. You could do

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 。这可能允许使用各种参数调用缓动器,例如当你有可能空的变量时。

You also could just check for typeof a == "undefined" etc, this would allow calling somefunction(undefined), where arguments.length is 1. This might allow easer calling with various parameters, e.g. when you have possibly-empty variables.

这篇关于Javascript中的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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