How do I wrap a function in Javascript?

前端 未结 6 1723
南笙
南笙 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:23

    Function wrapping in good old fashion:

    //Our function
    function myFunction() {
      //For example we do this:
      document.getElementById('demo').innerHTML = Date();
      return;
    }
    
    //Our wrapper - middleware
    function wrapper(fn) {
      try {
        return function(){
          console.info('We add something else', Date());
          return fn();
        }
      }
      catch (error) {
        console.info('The error: ', error);
      }
    }
    
    //We use wrapper - middleware
    myFunction = wrapper(myFunction);
    

    The same in ES6 style:

    //Our function
    let myFunction = () => {
      //For example we do this:
      document.getElementById('demo').innerHTML = Date();
      return;
    }
    
    //Our wrapper - middleware
    const wrapper = func => {
      try {
        return () => {
          console.info('We add something else', Date());
          return func();
        }
      }
      catch (error) {
        console.info('The error: ', error);
      }
    }
    
    //We use wrapper - middleware
    myFunction = wrapper(myFunction);
    

提交回复
热议问题