Reputation: 37909
My C# oriented braincells keep telling me that this should work:
var MyApp = function() {
currentTime = function() {
return new Date();
};
};
MyApp.currentTime();
Clearly it doesn't. But if a javascript function is an object, shouldn't I be able to call a function that is on the object? What am I missing?
Upvotes: 0
Views: 39
Reputation: 3933
You can change your code a bit and use this:
var MyApp = new (function() {
this.currentTime = function() {
return new Date();
};
})();
MyApp.currentTime();
Or you can do this:
var MyApp = {
currentTime: function() {
return new Date();
}
};
MyApp.currentTime();
Upvotes: 1
Reputation: 943571
currentTime
is a global (set when you call myApp
), not a property of MyApp
.
To call it, without redefining the function:
MyApp();
currentTime();
However, it sounds like you want either:
A simple object
var MyApp = {
currentTime: function() {
return new Date();
};
};
MyApp.currentTime();
A constructor function
var MyApp = function() {
this.currentTime = function() {
return new Date();
};
};
var myAppInstance = new MyApp();
myAppInstance.currentTime();
Upvotes: 2