Viacheslav Kondratiuk
Viacheslav Kondratiuk

Reputation: 8889

JavaScript: How to pass single global object to set of classes?

I have a set of global objects. Those globals can have different settings.

var s1 = {
    test1: 10,
    test2: 20
}

var s2 = {
    test1: 10,
    test2: 50
}
...

And I have set of classes which use those objects for self configuring. They could look like this:

var classA = function(s) {
    this.pA1 = s.test1 + s.test2;
    this.pA2 = Math.sqrt(s.test1);
}

var classB = function(s) {
    this.pB1 = s.test1 * s.test2;
    this.pB2 = s.test1 + s.test2 - s.test1 * s.test2;
}
...

Instances of those classes are:

var iA1 = new classA(s1);
var iB1 = new classB(s1);
...

var iA2 = new classA(s2);
var iB2 = new classB(s2);
...

In reality I have more settings, classes and instances.

How to do this without passing a parameter each time?

Upvotes: 0

Views: 54

Answers (1)

Oleg Sklyar
Oleg Sklyar

Reputation: 10082

function factory(s) {
    return {
        iA: new classA(s),
        iB: new classB(s),
        iC: new classC(s),
        iD: new classD(s)
    };
}

var set1 = factory(s1),
    set2 = factory(s2),
    ...

Alternatively:

function factory(constructors, arg1, arg2) {
    var res = {};
    for (var i in constructors) {
        var ctor = constructors[i];
        res[ctor.name] = new ctor(arg1, arg2);
    }
    return res;
}

var constructors = [ classA, classB, classC ];
var set1 = factory(constructors, s1),
    set2 = factory(constructors, s2),
    ...

Upvotes: 1

Related Questions