Okay, so this is complicated so try to bear with me, i will try to keep it as simple as possible:
I have a “class” Struct, that creates a “struct like” skeleton to apply to ArrayBuffers within Javascript. The problem is when I am attempting to mimic the ‘c’ like behavior of allowing a struct to contain other structs.
The problem is that it clobbers the iterator of the calling method (obviously a closure problem), that i cant seem to figure out.
Here is an example of the code that gets clobbered (hopefully this is enough code to get the answer, if not I will add more as necessary, just trying to keep extraneous code out of here):
function StructObject(){
this.applyBuf = function(buf, start){
var struct = {};
for (obj in this){
//problem is here:
console.log(obj); //prints "c" on the way in
struct[obj] = this[obj].__createFromBuf();
console.log(obj); //prints "foo" (see the structs below)
}
return struct;
}
}
function struct(strctObj, name){
var structObject = new StructObject();
...
//create the skeleton
for (item in strctObj){
//the specific code that fails me
structObject[item].__createFromBuf = function(buf, pos){
return structs[this.name].applyBuf(buf, pos);
}
...
//store the skeleton for later application
structs[name] = structObject;
}
//Creating structs looks like this:
new struct({ foo: type.INT }, "bar");
new struct({
a: type.INT, //defines size of memory (like c's sizeof)
b: type.LONG,
c: {type: type.STRUCT, name: "bar"},
d: type.SHORT}, "myStruct");
structs.myStruct.applyBuf(new ArrayBuffer(35));
When I iterate through the first struct on the class method applyBuf, it calls __createFromBuf on each item within the struct skeleton, if the item is another struct __createFromBuf calls applyBuf on the other “struct skeleton” object and returns an instance of that struct back to the calling struct, which works as intended.
JSFIDDLE — Here is the link to a working example 🙂
clean your
forstatements:if not declared properly, the
forloop index becomes a global member.demonstration: