JavaScript 不支持运算符重载,因此我认为您无法找到一种解决方案,让您可以逐字地使用+
复合-
年/月值。
但是,您可以使用加法和减法定义自己的年/月对象类型:
function YearsMonths(years, months) {
this.years = years;
if (months > 11) {
this.years = this.years += Math.floor(months/12);
this.months = months % 12;
}
else {
if (months < 0) {
this.months = 12 + (months % -12);
this.years -= (Math.floor(months/-12) + 1);
}
else {
this.months = months;
}
}
}
YearsMonths.prototype.add = function (otherYearsMonths) {
newYears = this.years + otherYearsMonths.years;
newMonths = this.months + otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
YearsMonths.prototype.subtract = function (otherYearsMonths) {
var newYears = this.years - otherYearsMonths.years,
newMonths = this.months - otherYearsMonths.months;
return new YearsMonths(newYears, newMonths);
}
然后像这样使用它:
value1 = new YearsMonths(65, 0);
value2 = new YearsMonths(47, 9);
value3 = value1.subtract(value2);
value4 = value1.add(value2);
value3.years;
# 17
value3.months;
# 3
value4.years;
# 112
value4.months;
# 9