javascript - Whats the quickest way to append or edit a function in an object? -


i have example object such:

var shooter = {fire : function(){shootrighthandgun("shotgun");}} 

however shooter finds new gun , want set shooters fire function this:

{fire : function(){shootrighthandgun("shotgun"); shootlefthandgun("handgun");}} 

what best/quickest way achieve this? helper functions, function array in object, anything. i'm totally open suggestions.

technically can edit functions getting function's source code via .tostring() method string manipulations on using regexp etc. very, messy , don't recommend it.

instead, give object bit more structure. first separate out right , left hand weapons:

var shooter = {     righthand : function () {},     lefthand : function () {},     fire : function () {} } 

now make .fire() method shoot (or use) weapons:

var shooter = {     righthandweapon : function () {},     lefthandweapon : function () {},     fire : function () {         this.righthandweapon();         this.lefthandweapon();     } } 

now, code above nothing (since both functions nothing) means code above unarmed shooter.

now can implement weapons functions:

function shotgun () {     /* code fire shotgun */ }  function handgun () {     /* code fire handgun */ } 

to complete can define following function well:

function unarmed () {}; 

now can arm shooter giving him weapons:

// armed shotgun shooter.righthandweapon = shotgun; shooter.fire();  // armed shotgun , handgun: shooter.righthandweapon = shotgun; shooter.lefthandweapon = handgun; shooter.fire();  // armed 2 shotguns: shooter.righthandweapon = shotgun; shooter.lefthandweapon = shotgun; shooter.fire();  // disarm shooter: shooter.righthandweapon = unarmed; shooter.lefthandweapon = unarmed; shooter.fire(); // nothing 

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -