Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inheritance

Tags:

javascript

oop

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.

like image 548
Tower Avatar asked May 30 '10 15:05

Tower


People also ask

What is JavaScript inheritance?

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.

Is there inheritance in JavaScript?

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.

What are the types of inheritance in JavaScript?

Mainly there are three types of inheritance in JavaScript. They are, prototypal, pseudo classical, and functional.

What is inheritance in ES6?

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.


1 Answers

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.

like image 62
Christian C. Salvadó Avatar answered Oct 21 '22 13:10

Christian C. Salvadó