Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, I suggest two changes in your code (that the examples will use): <code>this.storage</code> should be an object <code>{}</code>, since it looks like you never use it as an array. Also, <code>get</code> and <code>set</code> should be in the prototype, otherwise a new instance of those methods will be created for every instance object (unless a smart compiler optimises them, but we won't assume as much).</p> <p>Solution 1: you could perform quasi-inheritance, whereby only your storage <em>methods</em> are given to inheriting classes, but not the storage <em>object</em>:</p> <pre><code>function Storage(){} storage.prototype = { get: function(key){ return this.storage[key]; }, set: function(key, value){ this.storage[key] = value; } }; function Collection(){ this.storage = {}; } Collection.prototype = Storage.prototype; // quasi-inheritance function EixoCollection(){} EixoCollection.prototype = new Collection(); function OfertaCollection(){} OfertaCollection.prototype = new Collection(); var ofertaCollection = new OfertaCollection(); var eixoCollection = new EixoCollection(); ofertaCollection.set('mykey', 'myvalue'); alert(eixoCollection.get('mykey')); // undefined </code></pre> <p>Solution 2: Real inheritance, but instantiate a new store for every collection, so during the prototype lookup the function finds the local store. This is identical to the above, but the inheritance would be as before. So I'll just replace the line that's different:</p> <pre><code>Collection.prototype = new Storage(); // real inheritance </code></pre> <p>The problem with both of these implementations is that they require the inheriting class to do two things, both inherit the methods, and instantiate a store. Not pretty.</p> <p>The easy alternative, and maybe the most intuitive one is to make each use of <code>Storage</code> a composite object, and not an inherited one. A collection <em>has an</em> internal storage, and some extra functionalities, so it fulfils the <em>has-a</em> mnemonic making composition a valid candidate.</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