Not really that bad, unless you consider the fact that __proto__
is non-standard (but is used in most browsers). While some developers argue that __proto__
isn't going away soon, I'd rather go for a more "standard-ish" approach.
The usual way is to just use prototypes like they were designed:
// Person class
var Person = function(){
this.foo = 'hello';
this.bar = 'world';
};
Person.prototype = Object.create(Object.prototype);
// Since we just clobbered prototype, we return the constructor
Person.prototype.constructor = Person;
// Add in methods
Person.prototype.read = function(){/*...*/};
// Programmer class
var Programmer = function(){
// This is to run this object through the parent constructor so that it gets the properties.
Person.apply(this,arguments);
this.right = 'bob';
this.left = 'alice';
};
// Then "inherit" the parent methods
Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;
Programmer.prototype.readCode = function(){/*...*/};
console.log(new Person());
console.log(new Programmer());
Now it's pretty ceremonious at this point, all that prototype stuff. You can skip all that if you create functions that automate that. Some libraries do the same thing, with sugar:
var ChildClass = BaseClass.extend();
One problem with this style of encapsulation is that your methods are defined per instance rather than shared. This will eat up memory:
function Class(){
this.foo = function(){};
}
var instance1 = new Class();
var instance2 = new Class();
console.log(instance1.foo === instance2.foo); // false
Sometimes "forcing" private properties are just more hassle than originally intended. Besides, using the dev tools, your code is open to modification anyways. What most libraries do is use "pseudo-private", by prefixing the property with _
. Technically, these properties are public, but it's a common programming convention telling the developer it's private.
__proto__
by usingObject.create
– elclanrs Aug 27 '14 at 0:26