How do I wrap a function in Javascript?

前端 未结 6 1731
南笙
南笙 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

    The following wrapping utility takes a function and enables the developer to inject a code or wrap the original:

    
    function wrap(originalFunction, { inject, wrapper } = {}) {
    
        const wrapperFn = function(...args) {
            if (typeof inject === 'function') {
                inject(originalFunction, this);
            }
            if (typeof wrapper === 'function') {
                return wrapper(originalFunction, this, args);
            }
            return originalFunction.apply(this, args);
        };
    
        // copy the original function's props onto the wrapper
        for(const prop in originalFunction) {
          if (originalFunction.hasOwnProperty(prop)) {
            wrapperFn[prop] = originalFunction[prop];
          }
        }
        return wrapperFn;
    }
    

    Usage example:

    
    // create window.a()
    (function() {
    
        const txt = 'correctly'; // outer scope variable
        
        window.a = function a(someText) { // our target
            if (someText === "isn't") {
                throw('omg');
            }
            return ['a', someText, window.a.c, txt].join(' ');
        };
        
        window.a.c = 'called'; // a.c property example
    })();
    
    const originalFunc = window.a;
    console.log(originalFunc('is')); // logs "a is called correctly"
    
    window.a = wrap(originalFunc);
    console.log(a('is')); // logs "a is called correctly"
    
    window.a = wrap(originalFunc, { inject(func, thisArg) { console.log('injected function'); }});
    console.log(a('is')); // logs "injected function\na is called correctly"
    
    window.a = wrap(originalFunc, { wrapper(func, thisArg, args) { console.log(`doing something else instead of ${func.name}(${args.join(', ')})`); }});
    console.log(a('is')); // logs "doing something else instead of a(is)"
    
    window.a = wrap(originalFunc, {
        wrapper(func, thisArg, args) {
            try {
                return func.apply(thisArg, args);
            } catch(err) {
                console.error('got an exception');
            }
        }
    });
    a("isn't"); // error message: "got an exception"
    

    The last example demonstrates how to wrap your function with a try-catch clause

提交回复
热议问题