1

Im building an app's namespace and it looks as follows:

var app = {};
app.utils = {
    Expiration: function(){ // contructor
    ... // some code
    },
    init: (function(){
         app.utils.Expiration.prototype = function(){....}
      ())
};

But i get an error: TypeError: Cannot read property 'Expiration' of undefined, and actually it's true beacuse utils is still being defined, i know that i can define the prototype outside of the scope of app, my question is: can i define it inside app or app.utils with an self executing function or by any other means, thanks.

4
  • Why exactly don't you want to just define it after the initial util definition? Commented Apr 29, 2012 at 2:10
  • It might sound pedantic, but i just want my code to look complex. Commented Apr 29, 2012 at 2:17
  • 1
    @user1108631 - well, Javascript doesn't allow it so you can't do it regardless of how much you want it to look that way. app.utils is not properly defined until AFTER that entire declaration is done. Commented Apr 29, 2012 at 2:25
  • that's what i mentioned at the END on my post, but it's always good to read what others have to say about the internals of js. Commented Apr 29, 2012 at 2:31

1 Answer 1

5

You cannot refer to your own variable name in a static declaration. Your self executing function causes that to get evaluated and executed at the time of static declaration. Thus app.utils is not yet defined.

There are alternatives. Here's one:

var app = {};
app.utils = {};

app.utils.Expiration = function(){ // contructor
    ... // some code
    };

app.utils.Expiration.prototype = ...

Since each of these successive statements adds another level of properties, these statements have to get executed one after the other in this order so that the previous elements are in place.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.