Created
March 16, 2012 23:40
-
-
Save FireyFly/2053624 to your computer and use it in GitHub Desktop.
Inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
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 :-) )
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
Nice! There is one part I don't understand:
If we create one of these:
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:
Then 'fly' will have an own property of 'getMD5HashedSecret' and a [[Prototype]] with two properties, eat and walk.