Note that there are some explanatory texts on larger screens.

plurals
  1. POOverloading Arithmetic Operators in JavaScript?
    primarykey
    data
    text
    <p>This is the best way I can think of phrasing this question, given this JavaScript "class" definition:</p> <pre><code>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; }; }; </code></pre> <p>and the following test setup code:</p> <pre><code>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" </code></pre> <p>Is there any way of implicitly creating <code>q4</code> as a <code>Quota</code> object using the addition operator as follows...</p> <pre><code>var q4 = q1 + q2 + q3; console.log("Quota 04 is " + q4.toString()); // Prints "Quota 04 is 86400000" </code></pre> <p>rather than resorting to...</p> <pre><code>var q4 = new Quota(q1 + q2 + q3); console.log("Quota 04 is " + q4.toString()); // Prints "Quota 04 is 24:00:00" </code></pre> <p>If not what are the best practice recommendations in this area for making custom numeric JavaScript objects composable via the arithmetic operators?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload