Monkey Patching in Javascript

29 / May / 2015 by Vineeta Sharma 0 comments

Monkey Patching

The Monkey patching is a concept which is used to extend the behavior of a function without changing its original source code. We can add some extra functionality which can work a long with the original functionality(Before or after depends on the use case). The original function may be from third party module or it can be your own function. Popularly known as duck punching.

Here is the sample code where we can see how Monkey Patching happens.

[js]

var myDb = {
_password: ‘PASSWORD’,
_username: ‘VINI’
}

function Auth() {
/*something here*/
}

// Original method

Auth.prototype.login = function (username, password) {
// login method code
if (username == myDb._username && password == myDb._password) {
return username + ‘ logged in successfully!’;
}
else {
return ‘Sorry! Spammer ‘;
}
}

var newAuth = new Auth();
console.log(newAuth.login(‘vini’, ‘password’));

[/js]

Output:

[js]

//Sorry! Spammer

[/js]

Explaination of previous code

Here Auth is the function which contains, login function. What we want to achieve, is override this login function. We can do it either rewrite the previous code but in most of the cases we do not know the prototype of the code and we just dont want to mess around with the existing one. So here Monkey Patching comes into play.

Below is a sample snippet to override this login method with the help of Monkey Patching.

[js]

// add some operation before and after the original method.

newAuth.login = (function (original) {
return function (username, password) {
// before method calling alter the original arguments
var newUsername = username.toUpperCase();
var newPassword = password.toUpperCase();
console.log(‘password::’, newPassword, ‘username::’, newUsername);
var result = original.apply(this, [newUsername, newPassword]);
// after
// here work on result to alter original output
console.log(‘Result =’, result);
}
})(newAuth.login);

newAuth.login(‘vini’, ‘password’)

[/js]

Output:

[js]

//password:: PASSWORD username:: VINI

//Result = VINI logged in successfully!

[/js]

So what exactly we have done here is, we can see additional logging with its normal working. With some simple lines of code we have successfully overrided login method without changing its original functionality. All thanks to “Monkey Patching”.

Hope this helps.

FOUND THIS USEFUL? SHARE IT

Tag -

OOjs

Leave a Reply

Your email address will not be published. Required fields are marked *