Это самый лучший способ, которым я могу думать формулируя этот вопрос, учитывая это JavaScript «класс» определение:Перегрузка арифметических операторов в JavaScript?
var Quota = function(hours, minutes, seconds){
if (arguments.length === 3) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.totalMilliseconds = Math.floor((hours * 3600000)) + Math.floor((minutes * 60000)) + Math.floor((seconds * 1000));
}
else if (arguments.length === 1) {
this.totalMilliseconds = hours;
this.hours = Math.floor(this.totalMilliseconds/3600000);
this.minutes = Math.floor((this.totalMilliseconds % 3600000)/60000);
this.seconds = Math.floor(((this.totalMilliseconds % 3600000) % 60000)/1000);
}
this.padL = function(val){
return (val.toString().length === 1) ? "0" + val : val;
};
this.toString = function(){
return this.padL(this.hours) + ":" + this.padL(this.minutes) + ":" + this.padL(this.seconds);
};
this.valueOf = function(){
return this.totalMilliseconds;
};
};
и следующий код установки испытания:
var q1 = new Quota(23, 58, 50);
var q2 = new Quota(0, 1, 0);
var q3 = new Quota(0, 0, 10);
console.log("Quota 01 is " + q1.toString()); // Prints "Quota 01 is 23:58:50"
console.log("Quota 02 is " + q2.toString()); // Prints "Quota 02 is 00:01:00"
console.log("Quota 03 is " + q3.toString()); // Prints "Quota 03 is 00:00:10"
Есть ли способ неявного создание q4
как Quota
объекта с помощью оператора сложения следующим образом ...
var q4 = q1 + q2 + q3;
console.log("Quota 04 is " + q4.toString()); // Prints "Quota 04 is 86400000"
Rathe г не прибегать к ...
var q4 = new Quota(q1 + q2 + q3);
console.log("Quota 04 is " + q4.toString()); // Prints "Quota 04 is 24:00:00"
Если не то, что лучшие практические рекомендации в этой области для создания пользовательского числового JavaScript объектов компонуемы с помощью арифметических операторов?
Посмотрите на [SweetJS] (http://sweetjs.org/), который может сделать именно это. –
Здесь: https: // stackoverflow.com/q/10539938/632951 – Pacerier