Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I intercept a function called directly?

Tags:

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? } 
like image 371
yilmazhuseyin Avatar asked Aug 04 '10 14:08

yilmazhuseyin


2 Answers

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();     } })(); 

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.

like image 169
Andy E Avatar answered Sep 28 '22 05:09

Andy E


Function.prototype.callWithIntercept = function () {     alert("intercept");     return this.apply(null, arguments); }; 

var num = parseInt.callWithIntercept("100px", 10); 

It is worth noting that in newer versions of JS, there are Proxy objects you can use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

like image 27
Thomas Eding Avatar answered Sep 28 '22 05:09

Thomas Eding