Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inheritance
// The "common" wannabe-classical way, with closures for hiding.
function Person(secret) {
// secret is ignored
}
Person.prototype.eat = function() { ... }
Person.prototype.walk = function() { ... }
function ComputerSavvyPerson(secret) {
Person.call(this, secret)
this.getMD5HashedSecret = function() {
return md5(secret)
}
}
ComputerSavvyPerson.prototype = Object.create(Person.prototype)
function StupidPerson(secret) {
Person.call(this, secret)
this.tellSecret = function() { return secret }
}
StupidPerson.prototype = Object.create(Person.prototype)
@johnjbarton

This comment has been minimized.

Copy link

@johnjbarton johnjbarton commented Mar 17, 2012

Nice! There is one part I don't understand:

ComputerSavvyPerson.prototype = Object.create(Person.prototype)

If we create one of these:

var fly = new ComputerSavvyPerson('firey');

The result object will have a [[Prototype]] reference pointing to an object; that object will have a [[Prototype]] pointing to Person.prototype. I don't see what value we get from the extra intermediate object. Why not:

 ComputerSavvyPerson.prototype = Person.prototype;

Then 'fly' will have an own property of 'getMD5HashedSecret' and a [[Prototype]] with two properties, eat and walk.

@FireyFly

This comment has been minimized.

Copy link
Owner Author

@FireyFly FireyFly commented Mar 17, 2012

In practice, I'd think it isn't much of a difference in performance.

If you'd do ComputerSavvyPerson.prototype = Person.prototype however, and later do

ComputerSavvyPerson.prototype.getNerdyComputerInfo = function()  { ... }

you have a big problem since that would be visible on all objects inheriting from Person. Setting ComputerSavvyPerson.prototype = Person.prototype wouldn't really be "proper" inheritance.

(Heh, I didn't realise your post was a github comment and not an off-list reply at first :-) )

@johnjbarton

This comment has been minimized.

Copy link

@johnjbarton johnjbarton commented Mar 17, 2012

Yes, indeed. Which is why we typically write:

ComputerSavvyPerson.prototype = extend(Person.prototype);

Sadly extend() is a critical missing feature in JS with no advocates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment