Last Updated: January 04, 2017
·
14.29K
· dayjo

Joining multiple functions together in Javascript

I needed a way of adding some extra functionality to some existing functions but without wanting to touch the original functions' code.

This is what joint.js does.

First include the joint function in your script

function joint(a){var b;return b=a[a.length-1],a.pop(),a=a.length>1?joint(a):a[0],function(){b.apply(new a)}}

Then use it like this;

// My original function that I want to extend
function my_func() {
  console.log( "Original functionality." );
}

// Function with the new functionality
function new_func() {
  console.log( "New functionality." );
}

// Add the functionality of new_func to my_func 
my_func = joint([ my_func, new_func ]);

// Now run the original function with the new functionality
my_func();

/* CONSOLE OUTPUT:
 > Original functionality.
 > New functionality.
 */

You can download the source on my GitHub here: https://github.com/Dayjo/joint/ or take a look at it working on JSBin; http://jsbin.com/orIDujE/1/edit?js,console

Edit: Removed the two alternative versions in preference of just one which isn't particularly slower.

1 Response
Add your response

Or you can just extend it without using any external library:

var originalFunction = function() {
console.log("Original Function");
},
oldFunction = originalFunction,
originalFunction = function() {
oldFunction.apply(this, arguments);
console.log("Do something else after old function finished");
};

over 1 year ago ·