Note that there are some explanatory texts on larger screens.

plurals
  1. POImplementing instance methods/variables in prototypal inheritance
    text
    copied!<p>I've been playing around with prototypal inheritance after reading <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow noreferrer">http://javascript.crockford.com/prototypal.html</a> and having a bit of a problem with understanding how I could make use of it in the way I would use classical inheritance. Namely, all functions and variables inherited by the prototype essentially become statics unless they are overwritten by the child object. Consider this snippet:</p> <pre><code>var Depot = { stockpile : [], loadAmmo : function (ammoType) { this.stockpile.push(ammoType); } }; var MissileDepot = Object.create(Depot); var GunDepot = Object.create(Depot); </code></pre> <p><code>stockpile</code> and <code>loadAmmo</code> definitely should be in the prototype, since both MissileDepot and GunDepot have them. Then we run:</p> <pre><code>MissileDepot.loadAmmo("ICBM"); MissileDepot.loadAmmo("Photon Torpedo"); alert(MissileDepot.stockpile); // outputs "ICBM,Photon Torpedo" alert(GunDepot.stockpile); // outputs "ICBM,Photon Torpedo" </code></pre> <p>This is expected because Neither <code>MissileDepot</code> nor <code>GunDepot</code> actually have <code>stockpile</code> or <code>loadAmmo</code> in their objects, so javascript looks up the inheritance chain to their common ancestor.</p> <p>Of course I could set GunDepot's stockpile manually and as expected, the interpreter no longer needs to look up the chain</p> <pre><code>GunDepot.stockpile = ["Super Nailgun", "Boomstick"]; alert(GunDepot.stockpile); // outputs "Super Nailgun,Boomstick" </code></pre> <p>But this is not what I want. If this were classical inheritance (say Java), loadAmmo would operate on MissileDepot and GunDepot's stockpile independently, as an instance method and an instance variable. <strong>I would like my prototype to declare stuff that's common to children, not shared by them.</strong></p> <p>So perhaps I'm completely misunderstanding the design principles behind prototypal inheritance, but I'm at a loss as how to achieve what I've just described. Any tips? Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload