Javascript对象调用其他对象粉碎迭代器

时间:2012-04-10 03:38:58

标签: javascript

好的,所以这很复杂,所以尽量忍受我,我会尽量保持简单:

我有一个“类”Struct,它创建一个“struct like”骨架,以应用于Javascript中的ArrayBuffers。问题是当我试图模仿允许结构包含其他结构的'c'行为时。

问题是它破坏了调用方法的迭代器(显然是一个闭包问题),我似乎无法弄明白。

这是一个被破坏的代码示例(希望这是足够的代码来获得答案,如果不是,我会在必要时添加更多代码,只是试图将无关的代码保留在这里):

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));

当我遍历类方法applyBuf的第一个结构时,它会对结构骨架中的每个项调用__createFromBuf,如果该项是另一个结构__createFromBuf,则在另一个“struct skeleton”对象上调用applyBuf并返回该实例struct返回调用结构,它按预期工作。

JSFIDDLE - 以下是工作示例的链接:)

1 个答案:

答案 0 :(得分:1)

清理您的for声明:

如果未正确声明,for循环索引将成为全局成员。

<强>示范:

for (item in strctObj) // item becomes a global member

for (var item in strctObj) // item is scoped within the loop's owner function