How do I wrap a function in Javascript?

前端 未结 6 1708
南笙
南笙 2020-12-12 16:48

I\'m writing a global error handling \"module\" for one of my applications.

One of the features I want to have is to be able to easily wrap a function with a t

6条回答
  •  醉梦人生
    2020-12-12 17:12

    Personally instead of polluting builtin objects I would go with a decorator technique:

    var makeSafe = function(fn){
      return function(){
        try{
          return fn.apply(this, arguments);
        }catch(ex){
          ErrorHandler.Exception(ex);
        }
      };
    };
    

    You can use it like that:

    function fnOriginal(a){
      console.log(1/a);
    };
    
    var fn2 = makeSafe(fnOriginal);
    fn2(1);
    fn2(0);
    fn2("abracadabra!");
    
    var obj = {
      method1: function(x){ /* do something */ },
      method2: function(x){ /* do something */ }
    };
    
    obj.safeMethod1 = makeSafe(obj.method1);
    obj.method1(42);     // the original method
    obj.safeMethod1(42); // the "safe" method
    
    // let's override a method completely
    obj.method2 = makeSafe(obj.method2);
    

    But if you do feel like modifying prototypes, you can write it like that:

    Function.prototype.TryCatchWrap = function(){
      var fn = this; // because we call it on the function itself
      // let's copy the rest from makeSafe()
      return function(){
        try{
          return fn.apply(this, arguments);
        }catch(ex){
          ErrorHandler.Exception(ex);
        }
      };
    };
    

    Obvious improvement will be to parameterize makeSafe() so you can specify what function to call in the catch block.

提交回复
热议问题