Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  26] [ 5]  / answers: 1 / hits: 20155  / 12 Years ago, wed, march 14, 2012, 12:00:00

MDN says that valueOf and getTime are functionally equivalent. Why have two functions that do the very same thing?


More From » date

 Answers
39

The Date.prototype.getTime method returns the number of milliseconds since the epoch (1970-01-01T00:00:00Z); it is unique to the Date type and an important method.


The Object.prototype.valueOf method is used to get the "primitive value" of any object and is used by the language internally when it needs to convert an object to a primitive. For the Date class, it is convenient to use the "time" attribute (the value returned by getTime()) as its primitive form since it is a common representation for dates. Moreover, it lets you use arithmetic operators on date objects so you can compare them simply by using comparison operators (<, <=, >, etc).


var d = new Date();
d.getTime(); // => 1331759119227
d.valueOf(); // => 1331759119227
+d; // => 1331759119227 (implicitly calls "valueOf")
var d2 = new Date();
(d < d2); // => true (d came before d2)

Note that you could implement the "valueOf" method for your own types to do interesting things:


function Person(name, age) {this.name=name; this.age=age;}
Person.prototype.valueOf = function() {return this.age; }

var youngster = new Person('Jimmy', 12);
var oldtimer = new Person('Hank', 73);
(youngster < oldtimer); // => true
youngster + oldtimer; // => 85

[#86840] Tuesday, March 13, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
roberts

Total Points: 212
Total Questions: 101
Total Answers: 101

Location: Philippines
Member since Thu, Apr 14, 2022
2 Years ago
;