2010-09-09 51 views
1

我有麻煩使用shift()來調用我放入數組中的函數。我列舉了一個說明問題的簡單例子。使用myFuncArray.shift()()來調用函數

本質上函數被調用,但是,函數中變量的變化不會停留。

<html> 
<head> 
<script type="text/javascript"> 
Taco = function() {}; 
Taco.prototype.init = function() { 
    this.ex1 = "ex1 in init()"; 
    alert(this.ex1); 
}; 
</script> 
</head> 
<body> 
<input type="Submit" onClick="withShift();" value="withShift"/> 
<div id="div1"> 
</div> 
<input type="Submit" onClick="noShift();" value="noShift"/> 
<div id="div2"> 
</div> 
<script type="text/javascript"> 
// This calls init but does not hold the value of ex1 after the call 
withShift = function() { 
taco = new Taco(); 
    funcQ = []; 
    funcQ.push(taco.init); 
    funcQ.shift()(); 

    div1 = document.getElementById("div1") 
    div1.appendChild(document.createTextNode(taco.ex1)); 
}; 

// this calls init and it holds the value... 
noShift = function() { 
    taco2 = new Taco(); 
    taco2.init(); 
    div1 = document.getElementById("div2") 
    div1.appendChild(document.createTextNode(taco2.ex1)); 
} 
</script> 
</body> 
</html> 

非常感謝您的任何建議。

回答

1

當您傳遞方法指針時,JavaScript不記得this參數。您必須在函數對象上使用callapply方法來顯式傳遞this

當涉及到傳遞函數指針時,使用taco.init與使用Taco.prototype.init大致相同。下面是這將是工作方式:

taco = new Taco(); 
funcQ = []; 
funcQ.push(taco.init); 
// pass taco first, and the non-hidden function arguments after; 
// in this case, no other argument 
funcQ.shift().call(taco); 

如果您不能使用這種語法,你可以使用匿名函數:

taco = new Taco(); 
funcQ = []; 
funcQ.push(function() { taco.init(); }); 
funcQ.shift()(); 

在反對object.method語法不攜帶this的論點,封閉是可靠的。