So I've noticed that the result of
(new Date())
is a Date object; in this case
Date {Thu Dec 04 2014 22:43:07 GMT+0200 (SAST)}
but if I type
+(new Date())
I get an int value;
1417725787989
How is this done?
I have a function called 'Duration' which, when used like this:
new Duration(352510921)
returns an instance looking like this:
{ days:5, hours:3, mins:55, secs:10, ms:921 }
So how can I use the + operator to get the int value of the Duration instance?
var dur = new Duration(352510921);
console.log(+dur) // prints int value 352510921
The unary +
operator casts the instance to a Number
in the same way that calling the Number()
function will cast a variable to a Number
.
If you'd like to override how your specific instance is cast, you need to override the valueOf
property for that instance:
var a = {
valueOf: function () {
return 5;
}
};
console.log(a); //Object { valueOf: function () {...} }
console.log(+a); //5
From the ES5 standard:
11.4.6 Unary + Operator # Ⓣ Ⓡ Ⓖ
The unary + operator converts its operand to Number type.
The production UnaryExpression : + UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr)).
ToNumber
on an Object will then result in a ToPrimitive
with hint Number. ToPrimitive
will then call the [[DefaultValue]]
internal method which states:
When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:
- Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
- If IsCallable(valueOf) is true then,
- Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
- If val is a primitive value, return val.
- Let toString be the result of calling the [[Get]] internal method of object O with argument "toString".
- If IsCallable(toString) is true then,
- Let str be the result of calling the [[Call]] internal method of toString, with O as the this value and an empty argument list.
- If str is a primitive value, return str.
- Throw a TypeError exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With