Skip to content

Instantly share code, notes, and snippets.

@MichaelrMentele
Created July 12, 2016 04:43
Show Gist options
  • Save MichaelrMentele/213b2b8ff1121d84f6a4b035de39f961 to your computer and use it in GitHub Desktop.
Save MichaelrMentele/213b2b8ff1121d84f6a4b035de39f961 to your computer and use it in GitHub Desktop.

WTF Javascript!?

This was my initial reaction when introduced to prototypal inheritance. I was like, jeez, do you have to make it so awkward to instantiate objects? Why can't you just be like everyone else.

I feel vaguely guilty now, a little like that teacher who called young Einstein dumb. Turns out prototypal inheritance is awesome. Cue Highschool Musical and other stories of upsetting the status-quo.

So...

What is Prototypal Inheritance?

In a word it's delegation--not inheritance at all.

In Javascript 'ancestor' (prototype) objects are generic workhorses that do the common tasks that all its bossy 'children' don't want to do. The 'children' are snowflakes that have their individual unique methods--or should; I mean, you're not duplicating code are you?

Well, if you are using classes... then you are.

Classes vs Prototypes

In class based inheritance everything is a clone--like from star wars. Each object is stamped out of the same mold and shares the same behaviors (methods) as the rest of them.

In Javascript prototypes are slaves to any object that extends them. The advantage of this tyranny (who knew there were advantages to tyranny?) is that your code is more DRY. Think about the case when you have a 1,000 or a 1,000,000 instances--do you really want to duplicate shared behavior?

Since we are all obsessive about computational efficiency the answer is a clear: probably.

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