Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

js 运算符能重载吗?

例一个代码 xx + 10 转换成 一个方法调用传递参数(10)这种

用toString() valueOf() 的话一般是通过转换成字符串处理
但是字符串处理的话 默认+10 的话也就是字符串拼接。
能否重载运算符转化成方法调用


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

不能,JS不支持运算符重载。
JS里双目加号就是数字相加 或者字符串拼接。对象相加没什么含义,也是转为字符串或者数字再操作。
即便重写valueOf或toString或 Symbol.toPrimitive 也是绕不过这个规则。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...