我怎样才能拥有同一个Javascript模块的多个实例

How can I have multiple instance of same Javascript Module?

本文关键字:模块 实例 Javascript 同一个 拥有      更新时间:2023-09-26

假设我有以下模块

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?

将其分配为 this 的属性而不是局部变量。

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

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