in Development ~ read.

Classic Inheritance is not necessary in JS

It's finally happened. I've been told one too many times to explain JavaScript prototypes like classes. They are not and it's one of the reasons I like JS.

I was a little disappointed to see when ES6 announced the inclusion Classes which amounts syntactic sugar on top of prototypical inheritance. Prototypes support the cleaner code to avoid reusing methods and functions, but don't depend on a tightly coupled parent-child relationship. Super is expensive and should not be used carelessly.

I've written a lot of bad Backbone code, and it's so easy to extend a view from a parent, only to use some state-object or method render written on the parent. This can hide bugs, bloat abstractions and unnecessarily couple components.

This was exactly what Eric Elliot had some thoughts about thinking differently about about inheritance.


Prototypical Inheritance..evolved

When I learned to write 'OOJS' this was what we were shown.

function Person (name) {  
   this.name = name || 'Not Josh :(';
}

Person.prototype.sayName = function () {  
   return "My name is " + this.name;
}

var josh = new Person('Josh');  
console.log(josh.sayName()); //=> "My name is Josh"  

This was created to make developers comfortable with constructer functions and classes. Douglas Crockford has offered an improved Object.create style...

var prototype = {  
   sayName: function () {
     return "My name is " + this.name;
   }
}
var josh = Object.create(prototype);  
josh.name = 'Josh';  
console.log(josh.sayName()); //=> "My name is Josh"  

Summarized takeaways from Eric Elliot's talk

comments powered by Disqus