Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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