强制Javascript函数调用以调用Function.prototype.call方法

时间:2018-08-27 14:57:10

标签: javascript javascript-objects

有没有一种方法可以强制所有javascript函数调用来调用Function.prototype.callFunction.prototype.apply。 我计划围绕这些方法使用自定义填充程序,并希望每个函数调用都隐式调用这些方法之一。

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

1 个答案:

答案 0 :(得分:1)

拦截函数调用的唯一方法是访问Proxy them

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

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

 a();

但是,必须在执行陷阱之前显式代理所有功能。或者,如果该函数没有属性,则使用以下方法会更简单:

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

 a = wrap(a);
相关问题