Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Created March 16, 2012 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FireyFly/2053624 to your computer and use it in GitHub Desktop.
Save FireyFly/2053624 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link
Author

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
Copy link

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