2011-08-25 43 views
0

是否可以設置功能的'this'或調用者,但將其設置爲回叫?如何從回叫中指定主叫方

this.CallServer({ url: 'myurl', success: F.call(myDOMElement) }); 

F function(data){ $(this).text(data); } 

我意識到,我可以換回調函數,並傳遞一個DOMElement作爲PARAM調用˚F像下面,但我不知道是否有一種方法可以做到這一點更接近上方。

this.CallServer({url: 'myurl', success: function(data){F(data, myDOMElement);}}); 
F function(data, elem){ $(elem).text(data); } 

回答

3
this.CallServer({ url: 'myurl', success: F.bind(myDOMElement) }); 

bind將返回相同的功能,除了它具有的this固定值時調用。

Docs, including shim for older browsers.

簡單地說,bind可以定義爲:

func.bind = function(thisValue) { 
    return function() { 
     return func.apply(thisValue); 
    }; 
}; 

例如

var func = function() { return this }; 
var bound = func.bind([1, 2, 3]); 
var result = bound(); // [1, 2, 3] 
+0

太棒了!非常感謝你的迴應。 – Zholen