在Javascript / jQuery中包装函数 [英] Wrapping a function in Javascript / jQuery
问题描述
如果我有一个任意函数 myFunc
,我的目标是用一个在执行代码之前和之后运行代码的包装调用替换此函数,例如
If I have an arbitrary function myFunc
, what I'm aiming to do is replace this function with a wrapped call that runs code before and after it executes, e.g.
// note: psuedo-javascript
var beforeExecute = function() { ... }
var afterExecute = function() { ... }
myFunc = wrap(myFunc, beforeExecute, afterExecute);
但是,我没有实现所需的换行
功能。这样的jQuery中是否存在任何东西(我通过文档很好看但却看不到任何东西)?或者有人知道这方面的一个很好的实现,因为我怀疑有一堆边缘情况,如果我自己尝试自己编写,我会想念它吗?
However, I don't have an implementation of the required wrap
function. Is there anything that already exists in jQuery like this (I've had a good look through the docs but cannot see anything)? Alternatively does anybody know of a good implementation of this because I suspect that there are a bunch of edge cases that I'll miss if I try to write it myself?
(顺便说一句 - 这样做的原因是做一些功能的自动检测,因为我们在Javascript剖析器等不可用的封闭设备上做了很多工作。如果有比这更好的方法那么我也很欣赏这些问题的答案。)
(BTW - the reason for this is to do some automatic instrumentation of functions because we do a lot of work on closed devices where Javascript profilers etc. are not available. If there's a better way than this then I'd appreciate answers along those lines too.)
推荐答案
这是一个 wrap
函数,它将调用在
之前和之后的
函数具有完全相同的参数和,如果提供的话,此
:
Here’s a wrap
function which will call the before
and after
functions with the exact same arguments and, if supplied, the same value for this
:
var wrap = function (functionToWrap, before, after, thisObject) {
return function () {
var args = Array.prototype.slice.call(arguments),
result;
if (before) before.apply(thisObject || this, args);
result = functionToWrap.apply(thisObject || this, args);
if (after) after.apply(thisObject || this, args);
return result;
};
};
myFunc = wrap(myFunc, beforeExecute, afterExecute);
这篇关于在Javascript / jQuery中包装函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!