2013-10-08 44 views
0

可以說我有以下模塊我如何擁有相同的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?

回答

3

將它指定爲this的屬性而不是本地變量。

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

然後參考其與thisprototype方法。

相關問題