Skip to content

Instantly share code, notes, and snippets.

@dahjelle
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dahjelle/9690688 to your computer and use it in GitHub Desktop.
Save dahjelle/9690688 to your computer and use it in GitHub Desktop.
Add Before Advice (aspect-oriented) to a Function (using Sugar.js)

Assuming Sugar.js is installed, you can run this to add a before method to all functions.

Function.extend( {
    before: function( func ) {
        // TODO: could add ability to output function name (via this.toString() and a regex)
        // TODO: could add ability to modify arguments before getting passed to function
        var that = this;
        return function() {
            var args = Array.create( arguments );
            func.apply( that, args );
            return that.apply( that, args );
        };
    }
}, true );

This allows you to do something like:

var add = function( a, b ) {
    return a + b;
};

// other stuff

add = add.before( function( a, b ) {
    console.log( "add", a, b );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment