1

I have some JSON data, and I'm trying to create classes and methods dynamically based on that data:

var classes = JSON.parse(data);
var classesObj = {};

for(var c in classes){

  var methods = classes[c].methods;
  var methodsObj = {};

  for(var m in methods){

    methodsObj[m] = function(args){

      return methods[m].property;
    }

  }
 classesObj[c] = methodsObj; 
}

return classesObj;

But my problem is if I call something like

firstClass.firstMethod()

The property that is returned is actually from lastClass.lastMethod() I'm pretty sure it's an instantiation problem, but I just can't seem to figure out where to go from here.

Greg
  • 697
  • 1
  • 8
  • 22

1 Answers1

2

The problem is that the anonymous variables (c and m) are bound to the same variable outside of the your anonymous function. See Javascript closure inside loops - simple practical example.

Community
  • 1
  • 1
Steve Clanton
  • 4,064
  • 3
  • 32
  • 38