代码之家  ›  专栏  ›  技术社区  ›  Mickel

让对象在javascript中“调用”函数

  •  2
  • Mickel  · 技术社区  · 14 年前

    我不确定标题,但我希望你能帮助我。

    我希望使用类似于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?
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   Pointy    14 年前

    在函数原型上使用“call”或“apply”函数:

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

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

    调用接受像常规函数一样的参数列表,而apply希望参数在单个数组中。

    有些浏览器的旧版本没有“应用”,但我不知道现在是否值得担心。