Skip to content Skip to sidebar Skip to footer

Difference Between Classical Inheritance And Prototype Inheritance

I found this definition here : https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.y0nc8kx34 Doesn't it sound awkward to

Solution 1:

There are interface and semantic differences between "class" and "prototype".

Interface difference

How to use it in the code. Difference and benefits well explained in the article.

Semantic difference

No matter how it's implemented in javascript, we can use ES6-class to emphasize that our object has the "class" meaning. Originally "class" means that we can classify some object to one or another set of objects. See definition in set theory: https://en.wikipedia.org/wiki/Class_(set_theory) .

Also, class is something abstract and not exists before we create an instance.

If we talk about class inheritance - it's simple to understand the abstraction that some class can be a sub-class of another class creating hierarchy.

Prototype is a sample or representative object from some set of objects. in that case we create new objects using existing prototype (creating clone or link). And they also can be prototypes for new objects.

When other programmers will read your code and see what you choose - prototype or class, they expect those semantic meanings.

Solution 2:

In JavaScript, class inheritance is implemented on top of prototypal inheritance, but that does not mean that it does the same thing:

In addition to inheriting properties, class inheritance does extra wiring to link the child [[Prototype]] to the parent [[Prototype]]. Usually, the super() constructor is also called. Those extra steps form parent/child hierarchies and create the tightest coupling available in OO design.

Hence, "Classes inherit from classes and create subclass relationships: hierarchical class taxonomies."

It's also useful to understand that there is more than one kind of prototypal OO. Importantly, there is concatenative inheritance, and prototype delegation.

Concatenative inheritance is important, because that's what allows for simple (and very common) object composition in JavaScript. Remember the Gang of Four said, "favor object composition over class inheritance."

This is generally accepted OO design wisdom, and because of concatenative inheritance, it's a breeze to do that in JavaScript.

For a lot more detail, see "Master the JavaScript Interview: What's the Difference Between Class and Prototypal Inheritance?"

Post a Comment for "Difference Between Classical Inheritance And Prototype Inheritance"