js实现方法重载

高级编程语言中基本上有会用到方法的重载比如如下代码
        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格式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值