0

I'm trying to define functions in a loop in javascript...

for (var i in myArray) {
  Object.defineProperty(object, "field"+i, { ... });
}

...and each function needs to make use of a variable which is set in that loop...

for (var i in myArray) {
  Object.defineProperty(object, "field"+i, { 
    get: function() { return "some operation" + myArray[i]; }
  });
}

...but this doesn't work because when I call the functions (long after they're defined), i evaluates to the last item in the myArray. All of the functions I defined in the loop return the same (erroneous) value.

Can anyone tell me how to accomplish my aim: make use of myArray[i] within my getter function?

5
  • 2
    Take a look at this : developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…. Commented Apr 22, 2014 at 17:42
  • possible duplicate of Jquery Loop not working correctly? Commented Apr 22, 2014 at 17:42
  • @procrastinator, awesome. Thank you. I used a factory function to solve the problem. Commented Apr 22, 2014 at 17:48
  • Off-topic: for..in loops are a bad way of iterating arrays. You should use ES6 for..of (currently only supported by FF), or a for(var i=0, l=myArray.length; i<l; ++i) loop. Commented Apr 22, 2014 at 18:46
  • Not an awesome-sounding idea. Avoid array indices, which are more powerful than array elements? Support only a single browser? How about you give some indication of why for..in loops are a 'bad' way of iterating arrays? Commented Apr 23, 2014 at 1:38

2 Answers 2

1

I created an extra closure by using a factory function:

function makeGetter(myString) {
  return function () { return "some operation" + myString; };
}
for (var i in myArray) {
  Object.defineProperty(object, "field"+i, { 
    get: makeGetter(myArray[i])
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

this could be done as following

for (var i in myArray) 
  {
  var getter=function yourName () { return "some operation" + yourName.data;}
  getter.data=myArray[i];
  Object.defineProperty(object, "field"+i, { 
  get: getter});
  }

you can define a function with

 var test=function testit () {}

testit can be use to call the function from inside the function. its a locale variable inside, its replacing arguments.callee which is depreacted in strict mode.

test is defined outside the function to call it from outside

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.