What is differential inheritance in JavaScript?

This answer to the Object.create() method in JavaScript in SO talks about differential inheritance. The following is said:

These methods make it easy to implement differential inheritance, where objects can be directly inherited from other objects.

As far as I know, JavaScript always allowed objects to directly inherit from other objects through prototype inheritance. There is no class concept in JavaScript. So what does differential inheritance mean and why is it called that?

PS: I lost a comment on this answer a while ago, but I did not get any answers. Therefore, I wanted to check with a large and amazing community of SO JavaScript users.

+8
javascript prototype
source share
1 answer

As other commentators and related articles have already pointed out, differential inheritance is β€œjust” ordinary, well-known prototypical inheritance.

However, using the term differential inheritance, you focus on a cleaner template than JavaScript knows (although it’s pretty common in other prototypical languages ​​like Self, NewtonScript or Io). Unlike a pseudo-classic template, there are no constructors with new . Instead, using Object.create , you create a new object that inherits from the target object in one step, and then create the necessary instance properties (only those that differ) manually (not with a constructor). It is unusual to inherit from an object that you would consider an instance differently, and not from a selected prototype object.

 var object = Object.prototype; // a Person constructor and a Person.prototype method would be more familiar var person = Object.create(object); person.greet = function() { console.log("Hi, I'm "+this.firstName+" "+this.lastName); }; // as would new Person("John", "Doe"); var jo = Object.create(person); jo.firstName = "John"; jo.lastName = "Doe"; // but what now? We stay with "simple" Object.create here var ja = Object.create(jo); ja.firstName = "Jane"; jo.greet(); ja.greet(); 

As you can see, creating Jane is simple, but we would have to split with the new Constructor() template if we used it. This is why some JS gurus advocate using clean drawing around the world (so that you better understand what is going on) and are happy that Object.create was provided with EcmaScript 5.

However, using the constructor template and building generally accepted class hierarchies is common, useful, and truly possible in prototype languages. For example, Io will call the init method (if exists) every time you clone an object, and in the example above we could use it as well, which would make initializing Joe simpler:

 person.init = function(f, l) { this.firstName = f; this.lastName = l; return this; } var jo = Object.create(person).init("John", "Doe"); 

There is definitely no straight line to distinguish between differential and prototypical inheritance.

+8
source share

All Articles