Introduction
Sometimes, in JavaScript, we may need to exchange fundability of functions between them. Well, truly speaking, it is obviously not the best practice. But sometimes this tick may turn into benefits, if we use them in low counts and in controlled manner.
Background
Let's say we have two functions, 'showFirstName
' and 'showLastName
'.
Now, we want 'showFirstName
' to act exactly as 'showLastName
', which means replace the functionality of 'showFirstName
' with 'showLastName
's. And this is only for a certain period of time.
Using the Code
Here are our two functions:
function showFirstName(name){
alert('first Name: ' +name);
}
function showLastName(name){
alert('last Name: ' +name);
}
To assign functionality of 'showLastName
' to 'showFirstName
', we just have to do:
showFirstName = (function(){
return function(name){
return showLastName(name);
}
})();
After this exchange process, if we call the 'showFirstName
', it would work exactly like 'showLastName
':
showFirstName('Nitol')
Need To Be Careful !!!
- Once we made this exchange, '
showFirstName
' would work as 'showLastName
' all the time, from any scope. - The default behavior of '
showFirstName
' would be lost forever, unless we save its functionality to a variable, and at the end of our work, reassign its default using the variable.
var _realFunction = showFirstName;
showFirstName = (function(){
return function(name){
return showLastName(name);
}
})();
firstName = (function(){
return function(name){
return _realFunction(name);
}
})();
For a quick review, check out http://jsfiddle.net/f4x6f/ or use:
<input type='button' value='Show' id='btnShow'/> shows current functionality of function showFirstName
<br>
<input type='button' value='Change' id='btnChange'/> apply functionality of function showLastName
to showFirstName
<br>
<input type='button' value='Reset' id='btnReset'/> reset functionality of function showFirstName
back to itself
<br>
var _realFunction = null;
function showFirstName(name){
alert('first Name: ' +name);
}
function showLastName(name){
alert('last Name: ' +name);
}
$(document).ready(function(){
_realFunction = showFirstName;
$('#btnChange').click(function(){
showFirstName = (function(){
return function(name){
return showLastName(name);
}
})();
$('#btnShow').trigger('click');
});
$('#btnReset').click(function(){
firstName = (function(){
return function(name){
return _realFunction(name);
}
})();
$('#btnShow').trigger('click');
});
$('#btnShow').click(function(){
showFirstName('Dipon');
});
});