JavaScript does not have "inheritance" or "prototypal inheritance" or "classes" or any of that jazz... what you've been told, and how you've been taught about it, are a misunderstanding... all this nonsense about constructor functions and new
and such... that's all hogwash... well, it's all unnecessary effort, at best.
"Instead... only try to realize the truth... there is no spoon."
What JavaScript does have is "behavior delegation"... and object linking through the "prototype chain"... you merely link two instances of objects together, say Foo
and Baz
, and say that Baz
"delegates" to Foo
for any behavior that Baz
doesn't own itself but that Foo
does own. And thus, any object b
(aka, "b is an instance of Baz" in the more confusing terminology) which is linked to Baz
, delegates first to Baz
, and then to Foo
, for behavior.
That's it. Seriously. And function constructors and new
and all that stuff, everything you've read before about OO in JS, they're just distractions that lead you to the wrong mental model. And so is the new class
cruft (aka "sugar") that's coming in ES6. What's actually useful is the semantics of Object.create()
actually exposing how this stuff really works.
See what I mean below, comparing "2.js" (the old school and more confusing way) and "3.js" (the cleaner and "object linking and behavior delegation" way). They both do the same thing. But the latter actually says what it means, while the former masquerades as something it's not.
I added an example using ES6 class syntax and while it may add to the confusion and mislead people on what exactly the paradigm definition is I definitely think it is easier to read/write/maintain.
https://gist.github.com/4177454