我在从我编写的javascript类创建实例/对象时遇到问题。您能否查看代码并查看代码底部的输出。
提前致谢... 问候。
//MARKER MANAGER CLASS
var MarkerManager = (function(){
var arr = [];
var arrName = [];
var counter = 0;
var MarkerManager = function (args){
arr = [];
arrName = [];
counter = 0;
return {
addMarker: addMarker,
getMarker: getMarker,
getIndex: getIndex
}
};
function getIndex(){
return counter;
}
function addMarker(marker){
arrName[counter] = marker.name;
arr[counter] = marker;
counter++;
}
function getMarkerNameList(){
return arrName;
}
function getMarker(li_name){
var markerIndex = arrName.indexOf(li_name);
return arr[markerIndex];
}
/*var instance;
var _static = {
name: 'manager',
getInstance: function (args){
if(instance === undefined){
instance = new MarkerManager(args)
}
return instance;
}
};
return _static;
*/
return function (args){
var manager = new MarkerManager(args);
return manager;
}
})();
var marker1 = new Marker({name:'test0', lat:3 , lng:5, isDraggable:true, iconType:'red' });
var marker2 = new Marker({name:'test1', lat:33 , lng:55, isDraggable:true, iconType:'red' });
var marker3 = new Marker({name:'test2', lat:44 , lng:99, isDraggable:true, iconType:'red' });
var marker4 = new Marker({name:'test3', lat:55 , lng:77, isDraggable:true, iconType:'red' });
var marker5 = new Marker({name:'test4', lat:88 , lng:65, isDraggable:true, iconType:'red' });
var manager = new MarkerManager({test:'test2'}); //MarkerManager.getInstance({map:'testtt'});//
var manager2 = new MarkerManager({test:'test1'});
manager.addMarker(marker1);
manager.addMarker(marker2);
manager.addMarker(marker3);
manager2.addMarker(marker4);
manager2.addMarker(marker5);
alert(manager.getMarkerNameList());
alert(manager2.getMarkerNameList());
//output is "test0,test1,test2,test3,test4" for both manager objects. How can I separate them
答案 0 :(得分:2)
您需要移动所有变量&管理器对构造函数所需的函数。或者MarkerManagers将共享相同的变量&共同发挥作用。
var MarkerManager = (function(){
return function (args){
var arr = [];
var arrName = [];
var counter = 0;
var MarkerManager = function (args){
arr = [];
arrName = [];
counter = 0;
return {
addMarker: addMarker,
getMarker: getMarker,
getIndex: getIndex
}
};
function getIndex(){
return counter;
}
function addMarker(marker){
arrName[counter] = marker.name;
arr[counter] = marker;
counter++;
}
function getMarkerNameList(){
return arrName;
}
function getMarker(li_name){
var markerIndex = arrName.indexOf(li_name);
return arr[markerIndex];
}
var manager = new MarkerManager(args);
return manager;
}
})();