2012-04-05 11 views
0

これは奇妙な問題です。下のjavascriptを指定すると、元のオブジェクトをラップする関数をnewFunctionsオブジェクトに含めることを期待していますが、ループ内で最後に発生したアクションのみを実行しています。 var actionToCallはcurrentActionが現在参照しているものへの参照をコピーすべきではありません。ループが反復するときには変更しないでください。私はここで困っている。オブジェクトから作成されたJavascriptオブジェクトは常に最後の要素を参照します

var typeArray = { 
    type1: { 
     function1: function() { 
     console.log("this is function 1"); 
     }, 
     function2: function() { 
     console.log("this is function 2"); 
     } 
    }, 
    type2: { 
     somefunction: function() { 
     console.log("this is some function") 
     } 
    }, 
    type3: { 
     blah: function() { 
     return; 
     }, 
     moreBlah: function(something) { 
     console.log(something); 
     }, 
     evenMore: function() { 
     console.log("I'm last!"); 
     } 
    } 
    }, 
     index, 
     typeIndex, 
     currentType, 
     actionIndex, 
     currentAction, 
     newFunctions = {}; 

    for(typeIndex in typeArray) { 
    currentType = typeArray[typeIndex]; 
    for(actionIndex in currentType) { 
     currentAction = currentType[actionIndex]; 

     console.log(currentAction.toString()); 

     newFunctions[actionIndex] = function() { 
     var actionToCall = currentAction; 

     console.log("about to run action"); 

     actionToCall.call(this); 

     console.log("action has been called"); 
     } 
    } 
    } 

    console.log(newFunctions); 

    for(index in newFunctions) { 
    (newFunctions[index])(); 
    } 

答えて

1

actionToCallがcurrentActionに割り当てられているからです。

currentActionはグローバルなので、値はループの繰り返しに合わせて変化し続けます。

ループが終了すると、currentActionがevenMoreに割り当てられます。

ここに、スコープを誘導する自己実行関数を使用した修正があります。

var typeArray = { 
    type1: { 
     function1: function() { 
      console.log("this is function 1"); 
     }, 
     function2: function() { 
      console.log("this is function 2"); 
     } 
    }, 
    type2: { 
     somefunction: function() { 
      console.log("this is some function") 
     } 
    }, 
    type3: { 
     blah: function() { 
      return; 
     }, 
     moreBlah: function(something) { 
      console.log(something); 
     }, 
     evenMore: function() { 
      console.log("I'm last!"); 
     } 
    } 
}, 
index, 
typeIndex, 
currentType, 
actionIndex, 
currentAction, 
newFunctions = {}; 

for(typeIndex in typeArray) { 
    currentType = typeArray[typeIndex]; 
    for(actionIndex in currentType) { 
     currentAction = currentType[actionIndex]; 

     console.log(currentAction.toString()); 

     //induce scope here so actionToCall keeps the current value of currentAction. 
     (function(){ 

      var actionToCall = currentAction; 
      newFunctions[actionIndex] = function() { 


       console.log("about to run action"); 

       actionToCall.call(this); 

       console.log("action has been called"); 
      } 
     })(); 
    } 
} 

console.log(newFunctions); 

for(index in newFunctions) { 
    (newFunctions[index])(); 
} 
関連する問題