2014-02-20 23 views
0

有沒有一種方法可以無約束地調用obj的inc?可以不綁定地調用對象的成員方法嗎?

function callIt(callback){ 
    callback(); 
} 

var obj = { 
    count: 0, 
    inc: function(){ 
     this.count++; 
    } 
}; 

callIt(obj.inc.bind(obj)); 
obj.count;// 1 

問題與我有關,因爲較舊的IE版本不支持方法綁定。

+2

看一看[如何進入回調中正確的'this' /背景?](http://stackoverflow.com/q/20279484/218196 )替代解決方案。 –

+1

我的建議是使用['es5-shim.js'](https://github.com/es-shims/es5-shim)(或同等版本),然後繼續處理更有趣的問題。或者,可以在[MDN的Function.bind文檔](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Bind)中找到填充/填充填充 – user2864740

+0

這是一個相關的來源與有趣的答案,這個主題:http://stackoverflow.com/questions/9644044/javascript-this-pointer-within-nested-function – Blauharley

回答

1

你可以使用一個函數值

callIt(function() { obj.inc(); }); 
+0

那麼爲什麼不只是使用[一個墊片]綁定? – user2864740

+0

@ user2864740 OP明確表示,由於IE限制,他們無法使用 – JaredPar

相關問題