js实现方法重载

来源:互联网 发布:mwc飞控源码2.5 编辑:程序博客网 时间:2024/06/02 03:26
高级编程语言中基本上有会用到方法的重载比如如下代码
        public decimal add(decimal d1, decimal d2)        {            return d1 + d2;        }        public decimal add(string d1, string d2)        {            decimal res = 0;            try {              res= decimal.Parse(d1) + decimal.Parse(d2);            } catch (Exception e) {                throw  new Exception("字符串转化decimal类型失败" + e.Message);             }            return res;        }


但是如果在js中这样写就会被覆盖,因为函数定义时的参数个数和函数调用时的参数个数没有任何关系

在函数中可以用f.arguments[0]和f.arguments[1]得到调用时传入的第一和第二个参数,比如无想把时间字符

串格式化,如果按照上面那种写法应该是如下代码

    String.prototype.getDate = function () {        var res = /\d{13}/.exec(this);        if (res != null)            var date = new Date(parseInt(res));        else            var date = new Date(this)        return date.format("yyyy-MM-dd HH:mm:ss");    }    String.prototype.getDate = function (format) {        var res = /\d{13}/.exec(this);        if (res != null)            var date = new Date(parseInt(res));        else            var date = new Date(this)        return date.format(format);    }

可是你在调用的时候会发现完全无法重载,所以我们可以借助arguments对象来变相的实现方法重载,

修改后代码如下:

    String.prototype.getDate = function () {        var res = /\d{13}/.exec(this);        if (res != null)            var date = new Date(parseInt(res));        else            var date = new Date(this)        if (arguments.length == 1) {//判断参数个数            return date.format(arguments[0]);//arguments[0]获取第一个参数        }        return date.format("yyyy-MM-dd HH:mm:ss");    }


这时候再试下就可以了:

str.getDate()//返回yyyy-MM-dd HH:mm:ss格式

str.getDate("yyyy-MM-dd")//返回yyyy-MM-dd格式

原创粉丝点击