如何拥有相同Javascript模块的多个实例?

时间:2013-10-08 19:56:28

标签: javascript

假设我有以下模块

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;
}());

我宣布它的3个实例

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

我如何获得

test1.alertMyIndex();

显示1而不是3?

1 个答案:

答案 0 :(得分:3)

将其指定为this的属性,而不是本地变量。

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

然后在this方法中使用prototype引用它。

相关问题