Mike T.
Mike T.

Reputation: 355

How can I have multiple instance of same Javascript Module?

Lets say I have the following module

var TestModule = (function () {
var myTestIndex;

var module = function(testIndex) {
    myTestIndex = testIndex;
    alertMyIndex();
};

module.prototype = {
    constructor: module,
    alertMyIndex: function () {
        alertMyIndex();
    }
};

function alertMyIndex() {
    alert(myTestIndex);
}

return module;
}());

And I declare 3 instances of it

var test1 =  new TestModule(1);
var test2 = new TestModule(2);
var test3 = new TestModule(3);

How do i get

test1.alertMyIndex();

to show 1 instead of 3?

Upvotes: 0

Views: 60

Answers (1)

alex
alex

Reputation: 490263

Assign it as a property of this instead of a local variable.

var module = function(testIndex) {
    this.myTestIndex = testIndex;
    alertMyIndex();
};

Then refer to it with this within prototype methods.

Upvotes: 3

Related Questions