2011-09-29 99 views
2

我有代碼的Javascript委託

function createDelegate(object, method) 
{ 
    var shim = function() 
    {     
     method.apply(object, arguments); 
    } 
    return shim; 
} 


this.test = 3; 
var pAction = {to: this.test} 
this.tmp = createDelegate(this, function() 
{ 
       print("in: " + pAction.to); 
       return pAction.to; 
}); 
print("out: " + this.tmp()); 

但由於某些原因,我得到以下結果

​​

任何人都知道這樣做的原因如下?

+1

FWIW,你的代碼基本上試圖效仿ES5'.bind()'方法。 [查看MDN文檔](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind)以查看它們的實現。 –

+0

笏輸出你期望在「出」? – AmGates

+0

謝謝Felix Kling。要看看它。 – JMCampos

回答

6

當您創建委派的功能,您必須返回舊函數的結果:

function createDelegate(object, method) 
{ 
var shim = function() 
{     
    return method.apply(object, arguments); 
} 
return shim; 
} 
+0

工作。我的部分是什麼菜鳥錯誤...... – JMCampos

+0

是不是隻委託JS中的閉包? – masterach