Multiplication With Date Object - Javascript
Solution 1:
What's happening under the hood?
The short version:
Because it's being used in a math operation, the date is converted to a number, and when you convert dates to numbers, the number you get is the milliseconds-since-the-Epoch (e.g., getTime()
).
The long version:
The multiplication operator calls the abstract operation
ToNumber
on its operands.For objects like
Date
s, that calls the abstract operationToPrimitive
on the object, with the "preferred type" being "number".For most types of objects (including
Date
s),ToPrimitive
calls the abstract operation[[DefaultValue]]
, passing along the preferred type as the "hint".[[DefaultValue]]
with hint = "number" callsvalueOf
on the object. (valueOf
is a real method, unlike the abstract operations above.)For
Date
objects,valueOf
returns the "time value," the value you get fromgetTime
.
Side note: There's no reason I can think of to use var timeStamp = 1 * new Date()
rather than, say, var timeStamp = +new Date()
, which has the same effect. Or of course, on any modern engine (and the shim is trivial), var timeStamp = Date.now()
(more on Date.now
).
Solution 2:
Numeric conversion
It is because of numeric conversion in javascript which is almost same like toString but internally it is called much more often.
Numeric conversion is performed in two main cases:
- In functions which needs a number: for example Math.sin(obj), isNaN(obj), including arithmetic operators: +obj.
- In comparisons, like obj == 'John'. The exceptions are the string equality ===, because it doesn’t do any type conversion, and also non-strict equality when both arguments are objects, not primitives: obj1 == obj2. It is true only if both arguments reference the same object.
The explicit conversion can also be done with Number(obj).
The algorithm of numeric conversion:
If valueOf method exists and returns a primitive, then return it.
Otherwise, if toString method exists and returns a primitive, then return it.
Otherwise, throw an exception.
Among built-in objects, Date supports both numeric and string conversion:
alert( newDate() ) // The date in human-readable formalert( 1*newDate() ) // Microseconds from 1 Jan 1970
Post a Comment for "Multiplication With Date Object - Javascript"