+ in javascript

So, I noticed that the result

(new Date())

- Date object; in this case

Date {Thu Dec 04 2014 22:43:07 GMT+0200 (SAST)}

but if I print

+(new Date())

I get an int value;

1417725787989

How it's done?

I have a function called "Duration", which when used as follows:

new Duration(352510921)

returns an instance that looks 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
+4
source share
2 answers

The unary operator +passes the instance in Numberthe same way that calling the function Number()will cause the variable to change Number.

, valueOf :

var a = {
    valueOf: function () {
        return 5;
    }
};
console.log(a); //Object { valueOf: function () {...} }
console.log(+a); //5

ES5:

11.4.6 + # Ⓣ Ⓡ Ⓖ

unary + Number.

UnaryExpression: + UnaryExpression :

ToNumber ToPrimitive . ToPrimitive [[DefaultValue]] , :

O [[DefaultValue]] , :

  • valueOf [[Get]] O "valueOf".
  • IsCallable (valueOf) , ,
    • val [[Call]] Of, O .
    • val , val.
  • toString [[Get]] O "toString".
  • IsCallable (toString) , ,
    • str to [string] [[Call]], O - .
    • str , str.
  • TypeError.
+5

valueOf.

> var foo = { days:5, hours:3, mins:55, secs:10, ms:921, valueOf: function() { return 1; }  }   
undefined
> -foo
-1
+3

All Articles