Douglas Crockford seems to like the following inheritance approach:
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
newObject = Object.create(oldObject);
It looks OK to me, but how does it differ from John Resig's simple inheritance approach?
Basically it goes down to
newObject = Object.create(oldObject);
versus
newObject = Object.extend();
And I am interested in theories. Implementation wise there does not seem to be much difference.
The JavaScript inheritance is a mechanism that allows us to create new classes on the basis of already existing classes. It provides flexibility to the child class to reuse the methods and variables of a parent class. The JavaScript extends keyword is used to create a child class on the basis of a parent class.
When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype.
Mainly there are three types of inheritance in JavaScript. They are, prototypal, pseudo classical, and functional.
The ES6 JavaScript supports Object-Oriented programming components such as Object, Class and Methods. Further in Classes we can implement inheritance to make child inherits all methods of Parent Class. This can be done using the extends and super keywords. We use the extends keyword to implement the inheritance in ES6.
The approach is completely different, the Resig technique creates constructor functions, this approach is also known as classical inheritance i.e.:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
}
});
var p = new Person(true);
As you see, the Person
object is actually a constructor function, which is used with the new
operator.
With the Object.create
technique, the inheritance is based on instances, where objects inherit from other objects directly, which is also known as Prototypal Inheritance or Differential Inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With