tags:

views:

62

answers:

3

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?
}
+4  A: 

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();
    }
})();
Andy E
Maybe I can change Function.constructor function so every returned function will have your wrapper around it.
yilmazhuseyin
@yilmazhuseyin: no, you can't. Changing the *Function* constructor would only allow you to override functions created with `new Function(str)`.
Andy E
yes you are right. function newConstructor(){alert("a");};Function.prototype.constructor = newConstructor;did not work.
yilmazhuseyin
+1  A: 

You could iterate over the global scope and replace any objects of function type you find which aren't "yours".

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

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