Possible Duplicate:
Javascript closure inside loops - simple practical example
I am trying to do something like this:
var obj = function(){
var members = ['a','b','c','d','e'];
for(var i in members){
inst[i] = function(){
console.log(i);
}
}
};
But when I do:
var inst = new obj();
inst.a(); inst.b(); inst.c(); inst.d(); inst.e();
It prints out e 5 times! Also, I would likely to be able to reference this
rather than using the name that I am instantiated the object as, but I cannot get that to work at all. The logic behind this is to use websockets to generate an API template client side. This is a rough demo that does basically the same type of thing (logically) but I am getting caught up in this technical issue and it is keeping me from progressing.
Thanks
EDIT
Let me give the complete issue. I didn't want to overload everyone but these solutions aren't working...
var SocketClient = function(config){
//platform specific stuff
var self = this;
var count = 0;
var socket = io.connect(config.address+':'+config.port);
var members = [];
socket.on('method',function(data){
console.log(data.name);
KovarApp.client[data.name] = addLogicMember(data.name);
console.log(KovarApp.client[data.name]);
});
var addLogicMember = function(n){
return function(config){
var callback = null;
if(typeof config.callback !== 'undefined'){
var callback = config.callback;
delete config.callback;
}
call({
method: n,
data: config,
callback: callback
});
};
};
var call = function(config){
var c = count++;
var timer = null;
socket.on('reply_'+c,function(data){
if(typeof config.callback === 'function'){
if(timer != null){
timer.clearTimeout();
}
config.callback(data);
timer = setTimeout(function(){
socket.removeAllListeners('reply_'+c)
},10000);
}
});
config.data.handle = c; //make sure that the server has the handle for this function call
socket.emit(config.method,config.data);
};
};
The server emits 5 functions to the client: login being the first function and getpatientinfo being the last function. On the server, I have it set up to console.log every reply. If I call any of the functions, it console.log's getpatientinfo because that is the string that it receives, meaning that on the client every single function is referencing the last received string (getpatientinfo). I have changed it according to some of the answers, but it still isn't working. Socket shouldn't be an issue here. The issue is obviously my front-end logic when generating members, as every member reflects the last added member.
Solved! See below! (THIS WASN'T CLOSURE!!!)