[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
Original function behaviour
Now if we want to change the function behaviour based on our data object.
Note: It is not suggested to update the existing function behaviour. Because it can introduce defect which are very hard to debug and resolve.
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 the existing function behaviour. Because it can introduce defect which are very hard to debug and resolve.
Comments
Post a Comment