Reputation: 3040
I can call parse method of Date object directly as follows:
alert(Date.parse("March 21, 2012"));
However I cannot do this:
alert(Date.getTime()); // TypeError: Date.getTime is not a function
That is how I get it working:
alert(new Date().getTime()); // works well
So why can't I call Date.getTime() directly like Date.parse()?
Underlying Question: I have written a class and I want to use some of its methods directly like Date.parse() above.
Upvotes: 0
Views: 137
Reputation: 96810
function Class() {
this.foo = function() { return 123; };
}
Class.bar = function() { return 321; };
Class.bar(); // 321
( new Class ).foo(); // 123
Upvotes: 1
Reputation: 18125
As others have pointed out, JavaScript uses prototypes to defined instance methods. You can however defined static methods as shown below. I am not trying to define the whole Date
object here, but rather show how its instance and static functions are defined.
// constructor defined here
function Date() {
// constructor logic here
}
// this is an instance method
DateHack.prototype.getTime = function() {
return this.time_stamp;
}
// this method is static
Date.parse = function(value) {
// do some parsing
return new Date(args_go_here);
}
Upvotes: 1
Reputation: 526593
getTime
is in Date.prototype
, which is used when constructing new Date()
objects.
parse
is in Date
itself, and thus is called directly rather than from a constructed object.
Here's a post about JavaScript prototypes for your reading pleasure.
Upvotes: 6
Reputation: 26502
In object-oriented programming, the former is called a static method, whereas the latter is called an instance method. An instance method requires an instance of the object has been instantiated (thus the new Date()
call is necessary). Static methods do not have this requirement.
Underlying Question: I have written a class and I want to use some of its methods directly like Date.parse() above.
After you have written your class, to add static methods, you will want to do:
MyClass.myStaticFunction = function() {
// Contents go here.
}
Upvotes: 3