Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to properly derive object with private vars using javascript (prototypal) inheritance
    text
    copied!<p>I am new to JavaScript's (prototypal) inheritance and I'm trying to learn more about it. I am using a simple observer pattern as example, in which I want observable objects to be derived from the 'subject' object. This is what I WANT to do:</p> <pre><code>function subject() { var callbacks = {} this.register = function(name, callback) { callbacks[name] = callback; } this.unregister = function(name) { delete callbacks[name]; } var trigger = function() { var a = arguments; var t = this; $.each(callbacks, function(name, callback) { callback.apply(t, a); }); } } list.prototype = new subject() function list() { var items = {} this.add = function(name, item) { items[name] = item; trigger('add', name); } this.remove = function(name) { delete items[name]; trigger('remove', name); } } </code></pre> <p>Now when using the code above like below, I run into my first problem:</p> <pre><code>var l = new list() l.register('observer1', function() { console.log(this, arguments) }); l.add('item1', 'value1'); // &lt;-- ReferenceError: trigger is not defined, trigger('add', name); </code></pre> <p>To continue testing I made the trigger function 'public' using this.trigger instead. Running my example again I run into the next problem:</p> <pre><code>var l = new list() l.register('observer1', function() { console.log(this, arguments) }); l.add('item1', 'value1'); // &lt;-- output: subject, ["add", "item1"] </code></pre> <p>The <code>this</code> object is <code>subject</code>, I want it to be <code>list</code>. My third problem occurs when creating another list:</p> <pre><code>var l2 = new list(); //Don;t register any observers l2.add('item1', 'value1'); // &lt;-- output: subject, ["add", "item1"] </code></pre> <p>The <code>callbacks</code> list is shared between the 2 lists.</p> <p>I've tried similar things with Object.create(new subject()) as well and run into similar problems.</p> <p>My 3 questions in this are:</p> <ol> <li>Can I have private methods that can be used in derived objects <strong>(and should I even care about having them private or public)</strong>?</li> <li>How can I have the <code>this</code> object I want <strong>(without needing to use function.call in the derived object, if possible)</strong>?</li> <li>How can I keep the <code>callbacks</code> list in the base object without it being shared?</li> </ol>
 

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