在这段代码中,我创建了一个名为someFunction的函数.然后我修改了Function.prototype.apply并调用方法.因此,我正在运行我的拦截代码(显示警报),而不是我的功能代码正在工作.但是"呼叫"和"应用"都不会拦截直接方法调用.是否有可能拦截这个?
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?
}
Run Code Online (Sandbox Code Playgroud)
And*_*y E 28
您只能通过在其位置设置另一个函数来覆盖已知函数(例如,您不能拦截所有函数调用):
(function () {
// An anonymous function wrapper helps you keep oldSomeFunction private
var oldSomeFunction = someFunction;
someFunction = function () {
alert("intercepted!");
oldSomeFunction();
}
})();
Run Code Online (Sandbox Code Playgroud)
请注意,如果someFunction在此代码更改之前已由另一个脚本别名/引用,则这些引用仍将指向替换函数不会覆盖的原始函数.
Function.prototype.callWithIntercept = function () {
alert("intercept");
return this.apply(null, arguments);
};
Run Code Online (Sandbox Code Playgroud)
var num = parseInt.callWithIntercept("100px", 10);
Run Code Online (Sandbox Code Playgroud)
值得注意的是,在较新版本的JS中,Proxy您可以使用以下对象:https:
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy