[JavaScript] Updating the existing function behaviour

Ever find a situation when you want to change the function behaviour without duplicating the existing function code. Then you must be looking for this example.

Our test data object
var user = {
    name: 'testWorker',
    isOnLeave: true

Original function behaviour
var startWork = function(user){

[run]   ->startWork(user);

Now if we want to change the function behaviour based on our data object.
startWork = (function(){
    //backup original function in private scope
    var _originalFn = startWork;
    //assign new behaviour
    return function(user){
            console.log('on leave...');
        } else {

[run]   ->startWork(user);
[output]->on leave...

//change data object
user.isOnLeave = false;
[run]   ->startWork(user);

Note: It is not suggested to update the existing function behaviour. Because it can introduce defect which are very hard to debug and resolve.


Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Application Design Notes

How to store user password at server!!!