Update
Your search @name , which is an instance variable. Pray for it on es.next, but we donβt have it yet. Maybe in two years.
If you need a clean API, here is your solution:
function Class(foo) { Class.priv(this).foo = foo; } Class.priv = (function() { var cache = [], uid = 1; return function(obj) { if (!this.__id) { this.__id = uid; cache[uid++] = {}; } return cache[this.__id]; }; }()); Class.prototype.bar = function() { console.log(Class.priv(this).foo); }
Store all data in the cache as a constructor function. No data clutters the object.
Original
However, there is no such thing as "private".
All you can do is create a local variable inside the function.
Constructor function
var Human = function(name) {
It has a local variable, which by the very definition of a local variable cannot be used outside the constructor function.
This means that you cannot access it in external code such as a prototype.
However, you can only do this with ES5
var Human = function(name) { Object.defineProperty(this, "name", { value: name }); }
If you can really achieve what you ask for, you will make a huge breakthrough in js. I tried to do this for hours.
Another template:
var Human = function(name) { this.name = name; return { Shout: this.Shout.bind(this) }; } Human.prototype.Shout = function() { console.log(this.name); }
This has the overhead of calling .bind and creating a new object for each instance.