Skip to main content
1 of 2
Chris West
  • 905
  • 8
  • 17

This is what I wrote about in a blog post about Classes, Private Members, & Prototypal Inheritance in JavaScript. 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:

(function(_) { Tree = function ( name, size ) { var hidden = { name: name, size: size }; this._ = function($) { return _ === $ && 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" 
Chris West
  • 905
  • 8
  • 17