0

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?

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • JavaScript is a function scope language. Also variables declared without `var` become global scope. Give [this](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) a read – Matthew.Lothian Feb 05 '14 at 22:48

2 Answers2

2

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();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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();
qwertynl
  • 3,912
  • 1
  • 21
  • 43