Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think all this discussion of prototypes is overkill, and not really all that helpful to your situation. You don't really need a prototype here, since all your instances of <code>Mario</code> are going to have their own value for <code>currentHp</code>. Likewise, you don't need to make <code>Mario</code> a true constructor and worry about having to remember the <code>new</code> keyword (although you can if you want).</p> <p>As far as I can tell, everything you're trying to do can be handled by closures, with the added bonus of keeping your private members (like <code>baseHP</code> and your logic for calculating HP) truly private. Try this:</p> <pre><code>var Mario = (function () { //"private" variable encapsulated by the closure var baseHp = 1; //"private" method for calculating HP given an instance's current HP var getHp = function (currentHp, value) { return currentHp * Enemy.baseHp + (value || 0); }; //in OOP terms, baseHp and getHp would be like private static members used by //the whole class. return function () { //another "private" variable, but this one is only for //the current instance. var currentHp = baseHp * 100; //instance: return { name: "Mario", hp: function (value) { return !!value ? currentHp = getHp(currentHp, value) : getHp(currentHp); } }; }; })(); </code></pre> <p>I've tested this in the console, and it seems to work fine:</p> <pre><code>//test var Enemy = { baseHp: 3 }; var log = console.log.bind(console); var mario = Mario(); //or new Mario(); either one is fine log(mario); log(mario.hp()); log(mario.hp(-20)); log(mario.hp()); </code></pre> <p>Try it out on jsFiddle: <a href="http://jsfiddle.net/jmorgan123/zkw2P/" rel="nofollow">http://jsfiddle.net/jmorgan123/zkw2P/</a></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