0

假设我有以下模块

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?

4

1 回答 1

3

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

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

this然后在prototype方法内引用它。

于 2013-10-08T19:57:30.480 回答