0

I'm just wondering what the "best" way to do namespacing in javascript is. I know this has been asked a million times, but I've seen many methods including simply declaring an object as your namespace containings its relevant variables and methods. Is this the preferred way or is it better to use the the protype construct as in:

function Namespace() {

}

Namespace.prototype.newMethod = function() {

};

//...

// now to use this:
var namespace = new Namespace();
namespace.newMethod();

I'd also like to know why one method is preferred over another.

4
  • After that, how do you propose you access members of the namespace? Creating an instance of the namespace? Accessing through Namespace.prototype? Commented Nov 9, 2010 at 21:31
  • yes, creating an instance of the object Commented Nov 9, 2010 at 21:32
  • Do you really want users creating instances of your entire namespace? Namespaces are usually global/singleton. Commented Nov 9, 2010 at 21:33
  • strager - i'm not sure..thats kind of the core of my confusion. I.e. when to use namespaces (in the static sense) vs. when to create objects (via prototype chaining). Commented Nov 9, 2010 at 21:36

1 Answer 1

1

You usually only use the prototype method when you will be creating instances of the Namespace "class". If the methods are intended to be static (as defined by other OO languages) then simply creating an object and sticking functions on it is the way to go.

In other words, with your code you will be unable to call Namespace.newMethod(). But you could do (new Namespace()).newMethod(). Each approach is for solving a different problem.

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

3 Comments

This is what I was getting at. Would you mind elaborating on which is good for what type of problem? Thanks
I'm having a tough time thinking outside the world of a typical statically typed OO language like Java. I need "namespaces" which have traditional class-like functionality (so I guess prototype chaining would be best here); but I also would occasionally need static methods (just as in an Java for instance).
You can easily combine the two. If you have a function you are using as a class, use .prototype.methodName to declare instance methods, and .methodName to declare static methods.

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.