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

3 ではなく 1 を表示するには?

4

1 に答える 1

3

thisローカル変数の代わりにプロパティとして割り当てます。

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

次に、メソッドthis内で参照しprototypeます。

于 2013-10-08T19:57:30.480 に答える