js调用无参函数

在实际做项目的过程中,时间格式的处理是常用的,比如把"/"替换成"-"且去掉后面的时间戳只显示日期,这个实现对于很多人来说是信手拈来了,先说一版简单的实现

    //res.date从服务器获取到的数据
    const d = new Date(res.date);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;

因为要复用所以抽成函数,但是有没有优化的空间呢

function getPrettyDate(date){
    const d = new Date(date);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;
}

 我在用vscode的时候有一个非常讨厌的地方,就是写完函数之后光标不会自动定位到括号里面,导致我要用鼠标点一下然后写参数,有没有不用传参的办法,这样就能偷懒了

//常规的调用方式
getPrettyDate("2021/06/18 9:44:30");
getPrettyDate("2021/06/18T9:44:30");

//期待的调用方式
getPrettyDate();

 当然不传参并不是什么也不传,而是不在括号里面传参,一番思索我把问题的重点放在了调用者上面,函数的调用者在函数内部是this,直接把this当参数就行了

function getPrettyDate(){
    const d = new Date(this);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;
}

//这是我们要实现的调用方式
"2021/06/18".getPrettyDate();

 可是问题来了,"2021/06/18"并没有这个方法,我们得想办法加上,"2021/06/18"是字符串对象可以直接调用原型里面的方法,所以我们加在String.prototype上面

String.prototype.getPrettyDate = function(){
    const d = new Date(this);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;
}

"2021/06/18".getPrettyDate();

 大功告成,但是如果服务器传过来的是数字呢

Number.prototype.getPrettyDate = function(){
    const d = new Date(this);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;
}

(1623981685073).getPrettyDate();

当然有一种万能的方法,直接放在Object.prototype里面

Object.prototype.getPrettyDate = function(){
    const d = new Date(this);
    const year = d.getFullYear();
    const date = d.getDate();
    const month = d.getMonth() + 1;
    return `${year}-${month}-${date}`;
}

(1623981685073).getPrettyDate();
"2021/06/18".getPrettyDate();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

free5156

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值