我不确定标题,但我希望你能帮助我。
我想使用与 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?
}
最佳答案
您在函数原型(prototype)上使用“调用”或“应用”函数:
handler.call(thingThatShouldBeThis, arg, arg, arg);
或
handler.apply(thingThatShouldBeThis, [arg, arg, arg]);
Call 像常规函数一样接受参数列表,而 apply 需要单个数组中的参数。
有些浏览器的旧版本没有“应用”,但我不知道现在是否值得担心。
关于javascript - 让对象 "invoke"在 JavaScript 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3590807/