Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is what I wrote about in a blog post about <a href="http://gotochriswest.com/blog/2012/11/14/javascript-classes-private-members-and-prototypal-inheritance/" rel="nofollow">Classes, Private Members, &amp; Prototypal Inheritance in JavaScript</a>. Basically you want to create a private variable accessor function unique to every object and then have those prototype methods call that private accessor function, supplying it with the key that is only available within the closure:</p> <pre><code>(function(_) { Tree = function ( name, size ) { var hidden = { name: name, size: size }; this._ = function($) { return _ === $ &amp;&amp; hidden; }; }; Tree.prototype.genus = function(){ return ((typeof this._(_).name !== 'undefined') ? this._(_).name : 'Hybridicus Maximus'); }; Tree.prototype.bulk = function(){ return ((typeof this._(_).size !== 'undefined') ? this._(_).size : '8') + ' ft'; }; Fruit = function( name, size ) { Tree.apply(this, arguments); }; Fruit.prototype = new Tree(); // Fruit.prototype = Tree.prototype; -- I know this can be used, too. Fruit.prototype.bulk = function(){ return ((typeof this._(_).size !== 'undefined') ? Math.floor(this._(_).size / 2) : '4') + ' lbs'; }; })({}); var pine = new Tree('Pine', 9); var apple = new Fruit('Apple', 6); console.log(pine.genus(), pine.bulk()); // Outputs: "Pine 9 ft" console.log(apple.genus(), apple.bulk()); // Outputs: "Apple 3 lbs" console.log(pine._(), pine._({})); // Outputs: "false false" because outside of closure </code></pre> <p>You will notice that the last line shows that private variables are not accessible outside of the closure and thusly can't be retrieved by third-party code unless made available by an accessor function.</p>
    singulars
    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.
 

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