Skip to main content


Showing posts from March, 2013

[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){ console.log('working...'); } [run] ->startWork(user); [output]->working... 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){ if(user.isOnLeave){ console.log('on leave...'); } else { _originalFn(user); } } })(); [run] ->startWork(user); [output]->on leave... //change data object user.isOnLeave = false; [run] ->startWork(user); [output]->working... Note: It is not suggested to update