我可以拦截直接调用的函数吗? [英] Can I intercept a function called directly?

查看:103
本文介绍了我可以拦截直接调用的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我创建了一个名为someFunction的函数。然后我修改了Function.prototype.apply并调用方法。因此,我正在运行我的拦截代码(显示警报),而不是我的功能代码正在工作。但是呼叫和应用都不会拦截直接方法调用。是否有可能拦截这个?

In this code I created a function called someFunction. Then I modified Function.prototype.apply and call methods. So instead of my function code is working I am running my interception code (which shows an alert). But neither "call" nor "apply" intercepts direct method call. Is it possiple to intercept this?

Function.prototype.call = function(){alert("call");};
Function.prototype.apply = function(){alert("apply");};
function someFunction(){}
window.onload = function(){
    someFunction.call(this); //call alert is shown
    someFunction.apply(this); //apply alert is shown
    someFunction(); //how can I intercept this?
}


推荐答案

你只能覆盖一个已知的通过在其位置设置另一个函数来起作用(例如,你不能拦截所有函数调用):

You can only override a known function by setting another function in its place (e.g., you can't intercept ALL function calls):

(function () {
    // An anonymous function wrapper helps you keep oldSomeFunction private
    var oldSomeFunction = someFunction;

    someFunction = function () {
        alert("intercepted!");
        oldSomeFunction();
    }
})();

请注意,如果 someFunction 已经是别名/在此代码更改之前由另一个脚本引用,这些引用仍将指向原始函数不被替换函数覆盖。

Note that, if someFunction was already aliased/referenced by another script before it was changed by this code, those references would still point to the original function not be overridden by the replacement function.

这篇关于我可以拦截直接调用的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆