需要挂接到javascript函数调用中,有什么方法可以做到这一点吗?

需要挂接到javascript函数调用中,有什么方法可以做到这一点吗?,javascript,Javascript,我正在尝试连接一个加载Facebook新闻提要的函数: UIIntentionalStream.instance && UIIntentionalStream.instance.loadOlderPosts(); 在Facebook.com上 有没有一种方法可以让我用自己的JavaScript实现这一点?基本上,我需要某种类型的回调-调用该函数时,我希望调用我自己的函数。尝试以下方法: var old = UIIntentionalStream.instance.loadOld

我正在尝试连接一个加载Facebook新闻提要的函数:

UIIntentionalStream.instance && UIIntentionalStream.instance.loadOlderPosts();
在Facebook.com上


有没有一种方法可以让我用自己的JavaScript实现这一点?基本上,我需要某种类型的回调-调用该函数时,我希望调用我自己的函数。

尝试以下方法:

var old = UIIntentionalStream.instance.loadOlderPosts;
UIIntentionalStream.instance.loadOlderPosts = function() {
    // hook before call
    old();
    // hook after call
};

只需在原始函数调用之前或之后,在任何需要的地方挂接即可。

更完整的方法是:

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

这确保了如果
loadOlderPosts
需要任何参数或使用此参数,它将获得正确版本的参数,如果调用方需要任何返回值,它将获得该值。在前面的文章中展开:我创建了一个函数,您可以调用该函数来执行此“挂钩”操作


额外好处:为了更好的衡量,你还应该把这一切都包装起来。

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

导出函数createHook(obj、targetFunction、hookFunction){
设温度=对象[targetFunction]
obj[targetFunction]=函数(…参数){
让ret=temp.apply(此参数为args)
if(ret&&typeof ret.then==='function'){
return ret.then((value)=>{hookFunction([value,args]);return value;})
}否则{
hookFunction([ret,args])
回程网
}
}
}
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]));
}