简体   繁体   中英

Force Javascript function invocations to call the Function.prototype.call method

Is there a way to force all javascript function invocations to call the Function.prototype.call or the Function.prototype.apply . I plan to have a custom shim around these methods, and want every function invocation to call either one of these methods implicitly.

Function.prototype.call = function(thisArg){ 
    console.log("this is my custom call method"); 
} 
a = function(){} 
a(); // Doesn't call my shim

The only way to intercept function calls is to Proxy them

  function a() { /*...*/ }

  a = new Proxy(a, {
    apply(fn, context, args) {
      console.log("custom things");
      return Reflect.apply(fn, context, args);
    }
 });

 a();

However all functions have to be proxied explicitly before the trap gets executed. Or if the function doesnt have properties it is way simpler with:

 function wrap(fn) {
   return function(...args) {
     fn.call(this, ...args);
   };
 }

 a = wrap(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM