Search code examples
javascriptjs-amd

AMD singletons and "inheritance" of "private" methods


I guess probably the most used technique to mimic classes and class-inheritance in Javascript, which is outside of the BIG frameworks is the Simple Javascript Inheritance solution from John Resig (http://ejohn.org/blog/simple-javascript-inheritance).
At least in the jquery ecosystem. Some people also have extracted the inheritance solution of backbone.js (which seems to be based on goog.inherits http://bolinfest.com/javascript/inheritance.php).

I like both solutions. But somehow I feel that there are simpler solutions, especially in some subareas, for instance Javascript singletons, that take into account the fact that JS has only objects.

Two books/blogs have impressed me a lot in this respect. The first was "Javascript Patterns" from Stoyan Stefanov (chapter "code reuse patterns"), especially "inheritance"/code reuse through an "extend" function (shallow copy).

The other was "AMD Module Patterns: Singleton" (http://unscriptable.com/2011/09/22/amd-module-patterns-singleton). This was quite fascinating:

Since AMD only executes the definition function once, we’ve essentially created a singleton.

So I want to have such AMD singletons, simply an object which is returned by the amd factory function/definiton function.

But I also want to have the possibility to "inherit"/reuse methods from other AMD singletons. This would be achievable with an extend function.

Now comes the question:
Extend just gives me the "public" methodes of AMD singleton modules, but I also want to have the "private ones" (closure scope functions).

I could inject a "extractAllMethods" method into singleton modules that return all (also private) their methods to the method caller and combine it with an extend to merge it into the new singleton, but is this a good solution?

Does anybody have a better solution to extract also the private methods out of an AMD singleton module?

Thanks in advance
Wolfgang


Solution

  • I found the solution by myself!

    I found a blog from the well respected Nicholas C. Zakas

    His solution for me is:
    I do not need private methods through closures.
    Closures make the code a lot of harder to maintain.
    So, with no private methods, I will just need extend or the prototype property.