需要挂钩到javascript函数调用,任何方式都可以这样做?

Rin*_*cke 12 javascript

我正试图加入一个加载Facebook新闻源的功能:

UIIntentionalStream.instance && UIIntentionalStream.instance.loadOlderPosts();
Run Code Online (Sandbox Code Playgroud)

在Facebook.com上.

有没有办法让我用自己的JavaScript做到这一点?基本上,我需要进行某种回调 - 当调用该函数时,我希望调用自己的函数.

小智 28

更完整的方法是:

var old = UIIntentionalStream.instance.loadOlderPosts;
UIIntentionalStream.instance.loadOlderPosts = function(arguments) {
    // hook before call
    var ret = old.apply(this, arguments);
    // hook after call
    return ret;
};
Run Code Online (Sandbox Code Playgroud)

这确保了如果loadOlderPosts期望任何参数或使用它,它将获得它们的正确版本以及如果调用者期望任何返回值它将获得它


Nie*_*sol 11

尝试这样的事情:

var old = UIIntentionalStream.instance.loadOlderPosts;
UIIntentionalStream.instance.loadOlderPosts = function() {
    // hook before call
    old();
    // hook after call
};
Run Code Online (Sandbox Code Playgroud)

只需在原始函数调用之前或之后挂钩即可.


Eri*_*and 6

在前面的文章中进行扩展:我创建了一个函数,您可以调用该函数来执行此“挂钩”操作。

hookFunction(UIIntentionalStream.instance, 'loadOlderPosts', function(){
    /* This anonymous function gets called after UIIntentionalStream.instance.loadOlderPosts() has finished */
    doMyCustomStuff();
});



// Define this function so you can reuse it later and keep your overrides "cleaner"
function hookFunction(object, functionName, callback) {
    (function(originalFunction) {
        object[functionName] = function () {
            var returnValue = originalFunction.apply(this, arguments);

            callback.apply(this, [returnValue, originalFunction, arguments]);

            return returnValue;
        };
    }(object[functionName]));
}
Run Code Online (Sandbox Code Playgroud)

奖励:您也应该将所有这些都包装好,以防万一。


Eri*_*sty 5

与上面埃里克的回答类似。使用 ES6 时,此函数适用于异步和同步函数:

export function createHook(obj, targetFunction, hookFunction) {
    let temp = obj[targetFunction]
    obj[targetFunction] = function (...args) {
        let ret = temp.apply(this, args)
        if (ret && typeof ret.then === 'function') {
            return ret.then((value)=>{hookFunction([value, args]); return value;})
        } else {
            hookFunction([ret, args])
            return ret
        }
    }
}
Run Code Online (Sandbox Code Playgroud)