Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Consider:</p> <pre><code>function ThingWithEvent() { var thing = {}, events = {}; function raise( key ) { if ( !events[ key ] ) { return; } for ( var i = 0; i &lt; events[ key ].funcs.length; i++ ) events[ key ].funcs[ i ](); } thing.subscribe = function ( key, func ) { if ( !events[ key ] ) { events[ key ] = { name: key, funcs: [] }; } events[ key ].funcs.push( func ); }; thing.doSomething = function () { alert( "doing something" ); raise( "X" ); }; return thing; } </code></pre> <p>So, each instance of <code>ThingWithEvent</code> will get it's own <code>events</code> object (which is a private member of the instance because it's a local variable of the constructor). </p> <p><code>raise</code> is a nested function inside the constructor which makes it a private method of the instance.</p> <p><code>this.subscribe</code> and <code>this.doSomething</code> are "privileged" methods of the instance. They <strong>and only they</strong> can access the private members and private methods of the instance.</p> <p>Btw, I defined a explicit <code>thing</code> object which represents the new instance. I do this instead of just using <code>this</code> (which represents the new instance by default), because it enables me to identify the new instance uniquely inside the constructor even in nested functions - no <code>var self = this;</code> hack necessary.</p> <hr> <p><strong>Update:</strong><br> This would be inheritance:</p> <pre><code>function Thing() { var thing = Object.create( new EventTarget ); thing.doSomething = function () { alert( "doing something" ); this.raise( "X" ); }; return thing; } function EventTarget() { var events = {}; this.raise = function ( key ) { if ( !events[ key ] ) { return; } for ( var i = 0; i &lt; events[ key ].funcs.length; i++ ) events[ key ].funcs[ i ](); } this.subscribe = function ( key, func ) { if ( !events[ key ] ) { events[ key ] = { name: key, funcs: [] }; } events[ key ].funcs.push( func ); }; } </code></pre> <p>Usage:</p> <pre><code>var thing = new Thing(); thing.subscribe( ... ); thing.doSomething( ... ); </code></pre>
 

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