Question

I have a bunch of "modules" which follow the "JavaScript Module Pattern" as described in this popular article. To my understanding these modules are a way to aggregate various bits of behavior into neat namespaces.

But what if I want to be able to create a unique object instance which accepts arguments? As it stands, I can't do that as all the data is shared/static. I want to be able to do this:

var foo = new Some.Namespace.Whatever.Foo(config);

I can't change the structure of the pattern as we've been using it for a while and it works very well. I just want to tweak it so I can throw some "classes" into it which work with non-static data.

Was it helpful?

Solution

Why not try this?

var MODULE = (function () {
  var my = {};

  my.SomeClass = SomeClass;
  function SomeClass(six) {
    this.six = six;
  }
  SomeClass.prototype.five = 5;

  return my;
})();

When you call var obj = new MODULE.SomeClass(6) it will give you a new object. obj.five is shared between all instances of SomeClass because it is attached to the prototype. However, obj.six is specific to that instance, because it is attached to obj.

Alternatively, you may not need for your class to be inside a module. You could use a class to replace the module where appropriate, because both modules and classes in this case have some overlapping functionality.

OTHER TIPS

This is probably overuse of the module pattern, but is this what you mean?:

var Some = (function() {
    var util = { /* ... */ };
    return {
        Namespace: (function() {
            return {
                Whatever: (function() {
                    var Foo = function(config) {
                        this.foo = config.foo || "foo";
                        this.bar = config.bar || "bar";
                    };
                    var Bar = function() {};
                    Foo.prototype.toString = function() {
                        return this.foo + " "  + this.bar;
                    };
                    return {
                        Foo: Foo,
                        Bar: Bar
                    }
                }())
            };
        }())
    };
}());

var foo = new Some.Namespace.Whatever.Foo({foo: "hello", bar: "world"});
foo.toString() // "hello world"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top