-1

I have following javascript code:

var oReg = new Object;
oReg.a = {size: 762, content: 0};
oReg.b = {size: 342, content: 0};
//...

for (var s in oReg) {
    oReg[s].set = function(i) {
        alert('#name of oReg item#: ' + i);
    }
}

Where is "#name of oReg item#" should be a, b etc
I think it should be begin with this, but I cant make it out.

andrew
  • 97
  • 1
  • 10

3 Answers3

3

It should be s instead of i, but unfortunately it isn't that simple because of the "infamous loop problem". You have to create a new scope on each iteration (functions create scopes), to be able to keep a reference to each value of s. Otherwise, your setter will always return the value of the last object key.

The following code should do it:

for (var s in oReg) {
    oReg[s].set = (function(key) {
        return function() {
            alert('#name of oReg item#: ' + key);
        }
    }(s));
}
Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

I know lots of people will start to cry seeing a call to eval in code, but that's really only dangerous when throwing user input into it. Therefore:

var oReg = new Object;
oReg.a = {size: 762, content: 0};
oReg.b = {size: 342, content: 0};

for (var s in oReg) {
    eval("oReg[s].set = function(i){alert('oReg."+s+": ' + i);}");
}
tomsmeding
  • 916
  • 7
  • 25
  • 1
    *"that's really only dangerous when throwing user input into it"*... you are right, but there are other reasons for avoiding `eval`: it's slow, more difficult for the compiler to optimize and the code is harder to maintain. – Felix Kling Mar 31 '13 at 22:52
  • Comments accepted, I guess I learned something today again :) Take bfavaretto's answer instead. – tomsmeding Mar 31 '13 at 22:55
0
var oReg = new Object;
oReg.a = {size: 762, content: 0};
oReg.b = {size: 342, content: 0};
//...

for (var s in oReg) {
    oReg[s].set = (function(s) {
        alert('#name of oReg item#: ' + s);
    })(s);
}

I think you trying do this.

Ilia Sidorenko
  • 2,157
  • 3
  • 26
  • 30