2010-08-28 106 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

相关问题