2013-10-08 4 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(); 
}; 

Затем обратитесь к нему с this внутри prototype методов.

Смежные вопросы