Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I was thinking about this particular subject recently and the limitations of the various approaches. The best solution I've been able to come up with is below. </p> <p>It seems to solve the problems with inheritance, instantiation and ecapsulation (at least from tests on Google Chrome v.24) although probably at a cost in memory usage.</p> <pre><code>function ParentClass(instanceProperty) { // private var _super = Object.create(null), privateProperty = "private " + instanceProperty; // public var api = Object.create(_super); api.constructor = this.constructor; api.publicMethod = function() { console.log( "publicMethod on ParentClass" ); console.log( privateProperty ); }; api.publicMethod2 = function() { console.log( "publicMethod2 on ParentClass" ); console.log( privateProperty ); }; return api; } function SubClass(instanceProperty) { // private var _super = ParentClass.call( this, instanceProperty ), privateProperty = "private sub " + instanceProperty; // public var api = Object.create(_super); api.constructor = this.constructor; api.publicMethod = function() { _super.publicMethod.call(this); // call method on ParentClass console.log( "publicMethod on SubClass" ); console.log( privateProperty ); } return api; } var par1 = new ParentClass(0), par2 = new ParentClass(1), sub1 = new SubClass(2), sub2 = new SubClass(3); par1.publicMethod(); par2.publicMethod(); sub1.publicMethod(); sub2.publicMethod(); par1.publicMethod2(); par2.publicMethod2(); sub1.publicMethod2(); sub2.publicMethod2(); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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