I was reading this article in the English SO and I came across the term differential inheritance .
What exactly is differential inheritance?
Is it possible to have a minimal example, preferably in JavaScript?
I was reading this article in the English SO and I came across the term differential inheritance .
What exactly is differential inheritance?
Is it possible to have a minimal example, preferably in JavaScript?
Complementing the bfavaretto response.
In languages like Java and .NET, instances are all bastards **, since only types have inheritance rights.
In Javascript, everyone can "inherit" everyone. Every Javascript object has a prototype. The prototype tells an object what properties it has via inheritance. And the language allows you to do such cool atrocities like this:
var foo = {}; // esse objeto herda de Object.
foo.prototype = Array.prototype; // E agora ele tem um protótipo comum com o Array :D
You can take this a step further.
var bar = {nome: "John Doe", idade: 21};
foo.prototype = bar; //sim, isso é permitido.
You can take it further ...
var bar = {nome: "John Doe", idade: 21};
var foo = function () {};
foo.prototype = bar;
var ni = new foo(); // sério, veja as propriedades de ni.
We have an adoption process here, because now the "parent" of foo
becomes bar
. The object's parent becomes another object, not a type.
Yes, these modern family relationships, with so tenuous ties, are actually quite complex ...
Seriously now: this story of inheriting from an object and not from a type is called differential inheritance. This gives a lot of power to the programmer - you can set inheritances dynamically and at run time , and with more flexibility than in the "traditional" OO template . But these powers bring great responsibilities, especially in a world where the only safe typing is the typing duck .** This is NOT a technical term;)
Wikipedia article (so skinny that we even suspect it):
Differential inheritance is a common inheritance model used in prototype-based programming languages such as JavaScript, Io, and NewtonScript. It operates on the principle that many objects derive from other more general objects, and only differ from them in few details; usually the derived object internally maintains a list of pointers to the more generic ones.
In this OS question , say differential inheritance is a synonym for but its use in relation to JavaScript is to emphasize the "pure" pattern in which Object.create
is used to inherit directly from another object, instead of new
, which is a device that JavaScript has to stay more like class-based languages (by the way, in ES6 we'll even have class
, but internally everything will continue to work in the same way, the inheritance will remain prototypical).