views:

118

answers:

1

Hey guys,

I follow a module pattern where I instantiate components, however, a lot of time a component will only be instantiate one time (example: a comment system for an article).

For now I instantiate in the same JS file. but I was wondering if it is the wrong approach? It kind of make no sense to instantiate in the same file and always only once. But at the same time, if this file is in the page I want to have access to my module without instantiate from elsewhere, and IF I need another instance, I just create another from elsewhere...

Here is the pattern I follow:

  ApplicationNamespace.Classname = function() {
      // constructor    
      function privateFunctionInit() {
          // private
      }
      this.privilegedFunction = function() {
          // privileged
          privateFunction();
      };
   privateFunctionInit()
  };
  ApplicationNamespace.Classname.prototype = {
      Method: function(){}
  }
  var class = new ApplicationNamespace.Classname();

What do you think, wrong approach, or is this good?

+2  A: 

I don't think there's anything inherently wrong with this. We have a lot of JS classes in the codebase at my job that uses this pattern. Even though you're essentially using the class as a singleton, structuring it this way allows you to create more instances in the future with ease, should you ever need to.

In my own projects, I tend not to instantiate JS classes from within the file that defines them. I have a separate script that will instantiate whatever classes are needed on a page and work with them accordingly. That approach is probably more modular, but if you're only ever using one instance, it's mostly a matter of preference.

If you're sure you're never going to use more than one instance of the class, you could simplify things by creating a singleton object with object literal notation.

Jimmy Cuadra
"you could simplify things by creating a singleton object with object literal notation." This, vote up.
Anders
Yea I know I could have used a singleton, I *might* need to instantiate it another time, My problem with instancing from another script happen when we are 2 or 3 guys working in the project, we might instantiate those scripts more than needed, or search to kjnow where it is instanciate, keeping it in the file tells other developers to use this instantiation unless you need something more specific.More to the point, the module is only loaded if needed.Still my approach just seems wrong
Cedric Dugas
I guess I could be wrong on this, might be better to really be a singleton, even if in the end, that is 2 pattern everyone needs to follow.
Cedric Dugas