Software Programming

Kunuk Nykjaer

Extend existing Javascript method

leave a comment »


Imagine you are dependent on a 3rd party Javascript function called print.
That method is called by various methods and maybe from a 3rd party component.
You want to hook into the method and do some extra stuff.
Here’s an example of how to ‘extend’ the 3rd party method.

// Simulate 3rd party function
var print = alert;

// Original method 
print('how are you?'); // alert with how are you?

// Immediate function which encapsulates temp variables
(function (origin) {
	// Update original method
	print = (function (origin) {
		function decoratedOrigin(input) {
			// Modified input
			var modifiedInput =
				input + ' injected at time: ' + new Date().getTime();

			// Injected method
			console.log(modifiedInput);

			// Invoke original method and return result
			return origin(modifiedInput);
		}
		return decoratedOrigin;
	})(origin);
})(print); // Inject with origin method

// Extended method		
print('how are you today?'); // alert and console.log with modified input
Advertisements

Written by kunuk Nykjaer

December 10, 2014 at 9:47 pm

Posted in Javascript

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: