Reputation: 5634
I noticed that now() can only be called by the Date object. getTime() can only be called by an instance of date.
var dd1 = new Date();
//console.log(dd1.now()); //Throws error -> TypeError: Object Mon Aug 19 2013 16:28:03 GMT-0400 (Eastern Daylight Time) has no method 'now'
console.log(dd1.getTime());
console.log(Date.now());
//console.log(Date.getTime()); //Throws error ->TypeError: Object function Date() { [native code] } has no method 'getTime'
Is there a formal name for this difference? Is this the difference between "static" and "non-static." When I create a new instance of Date, shouldn't all methods be inherited?
Upvotes: 8
Views: 10122
Reputation: 21430
I don't know if this answers your question but I think these two methods do different things.
Date.now()
gets "The number of milliseconds between midnight, January 1, 1970, and the current date and time."
Whereas, dateObj.getTime()
"Returns the number of milliseconds between midnight, January 1, 1970 and the time value in the Date object."
dateObj.getTime()
requires you to use an object reference, because it uses that to get the difference "between midnight, January 1, 1970 and the time value in the Date object."
You don't need to reference an object with the Date.now()
method because it doesn't use any object, it simply gets the "number of milliseconds between midnight, January 1, 1970, and the current date and time."
Ref. Date.Now()
Ref. dateObj.getTime()
Upvotes: 7
Reputation: 36438
"Static" vs "non-static" is one way to put it; also "object methods" vs. "class methods". You call now()
on the Date
class, not an object.
now()
is a factory method of the Date
class, creating and returning an object - in this case, a Date
representing the moment when now()
was called.
getTime()
requires an existing Date
object - it's giving you a property (in this case, a unix-time representation) of that object.
Class-level methods remain that, they don't get added to object instances. So when you create a Date
instance, yes, all the object methods are inherited. The class-level methods are not.
Upvotes: 5
Reputation: 413720
It's the difference between properties of the constructor object and properties of the constructor object's prototype. The "now" property is a property of the Date constructor itself, and not a property of Date.prototype
. It's the opposite situation for "getTime".
Semantically it makes sense: the concept of "now" is independent of any particular date instance. The "getTime" method is intended to report on the timestamp for the date actually represented by a particular date instance.
If you're defining your own constructors, you can create "class methods" (I personally would hesitate to call them that, but whatever) like this:
function MyConstructor() {
// ...
}
MyConstructor.someMethod = function() {
// ...
}
Then MyConstructor.someMethod()
calls that function independently of any particular instance of your class.
Upvotes: 10