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) |
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
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 doyou have a big problem since that would be visible on all objects inheriting from
Person
. SettingComputerSavvyPerson.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 :-) )