Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The singleton pattern he presents is pretty common and pretty powerful. It is a self-invoking module. It allows you to use the module pattern (very solid js pattern) and probably has less code than your method.

Also, javascript has closures, use them. this._private is a hacky java-esque way of doing things. return {public_methods...} is a solid way of working towards the strengths of the language and doing proper js encapsulation.

As for the prototype pattern, there are a million ways you can do that. Best to learn the fundamentals so you can use whatever works best based on the situation.

edit: I should add that one of the reasons I like JS patterns is that there are multiple correct ways to implement them based on the situation. There are many wrong ways too, of course :) but it is a very flexible language.



Here is what I prefer to call a singleton in JS, I don't think it could be any simpler than that:

  mySingleton = {
    initialized: false,

    init: function() {
      if (this.initialized == false) {
        this.initialized = true;
        // Initialize the singleton here
      }
      return this
    },
  }

  singleton1 = mySingleton.init()
  singleton2 = mySingleton.init()
Both underscore notation and returning "public" methods feel awkward in JavaScript, though the second appraoch introduces major trade-offs which I belive are not worth it. E.g. how do you create inheritance chains when using this pattern? Are you just copying public methods returned from one object into another? Or how do you inspect private properties in Dev Tools? Are you setting breakpoints for that purpose?




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: