2010-08-28 102 views
2

我不確定標題,但我希望你能幫助我。讓對象在JavaScript中調用函數

我想用有點相同的模式,jQuery使用他們的事件處理程序,如點擊/懸停/模糊等,你在事件處理程序中使用this來獲取對象。

我該如何做到這一點?

// The event handler 
var handler = function() { 
    alert(this); // how do I set "this" in the trigger? 
} 

// The function that triggers the event handler 
var trigger = function(handler) { 
    var o = someObject; 
    if($.isFunction(handler)) handler(); // how do I set "o" as the this-reference in handler? 
} 

回答

2

您可以使用「呼叫」或在函數原型「應用」功能:

handler.call(thingThatShouldBeThis, arg, arg, arg); 

handler.apply(thingThatShouldBeThis, [arg, arg, arg]); 

調用需要的參數列表像一個普通的功能, apply將參數放在單個數組中。

某些瀏覽器的舊版本沒有「應用」,但我不知道現在是否值得擔心。

+0

明白了,謝謝! – Mickel 2010-08-28 13:11:50

相關問題