javascript中valueOf和toString区别及调用时机

wxhhbdx wxhhbdx 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

Date.prototype.toString=function(){
return 11;
}
Date.prototype.valueOf=function(){
return 22;
}
var b1 = new Date();
var b2 = new Date();
console.log("b1.toString():"+b1.toString());
console.log("b1.valueOf():"+b1.valueOf());
console.log("b1+b2:"+(b1+b2));

function circle(){
this.toString=function(){
return 11;
};

this.valueOf=function(){
return 33;
}
}

var cir1 = new circle();
var cir2 = new circle();
console.log("cir1+cir2="+(cir1+cir2));

输出结果为:
b1.toString():11
b1.valueOf():22
b1+b2:22
cir1+cir2=66
为什么两个date对象相加调用的是其toString()方法,而两个circle对象相加,调用的却是其valueOf方法。
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
wxhhbdx
JavaScript 87,983 成员 224,680 内容