Inheritance

JavaScript supports prototype inheritance. In other programming languages, objects and classes inherit from each other to use each other's properties and functions. However, in JavaScript, you have an object-based inheritance, which is called a prototype, in which objects use the properties of other objects. For example, if you have a Person object, then you can use the _proto_ attribute for that object to create another Student object:

Inheritance

Prototype chaining

In JavaScript, you create new objects from existing objects. This process is called prototype chaining. It is similar to inheritance in object-oriented systems.

Description

Prototype is a property of the constructor function. When you add any object property to a prototype, it will add this property or method to the objects created by the constructor function. In prototype chaining, we create a function prototype using the properties of the constructor function. Using this, all methods or properties transfer to the prototype object from the constructor function. This method is very easy and useful for creating the constructor function to create objects. Here is an example:

function person(name) {
  this.name=name;
}
person.prototype= {
  sayHi:function() {
    console.log("something");
  }

  Function student(name) {
    This.name=name;
  }
}
Student.prototype=new Person();
Varstd=new student("Ali");
Std.sayHi();

In method resolution, first JavaScript checks objects for methods. When you use prototype chaining, it can override methods for prototypes of an object. So, the JavaScript construction function sets methods for objects.

Constructor stealing

In JavaScript, constructor stealing is also called classical inheritance. This method is use to inherit problems of prototype reference values.

Description

In constructor stealing, we call a super constructor in a subtype constructor. This idea is quite simple and easy. We use the call() and apply() methods for function calling. Here is an example:

function super() {
  this.name=["Ali"];
}
function sub() {
  super.call(this);
}

varstd=new sub();
std.name.push("Ali");
varstd1= new sub();
console.log(std1.name);

In this example, we used the call() method to call a super constructor for a newly created subclass instead of a subconstructor. This will initialize all objects in the super() function on sub().

Note

When we use prototype chaining, the constructor function will allow us to pass arguments from a super constructor to within the subconstructor.

Combination inheritance

Combination inheritance is also called pseudo-classical inheritance. This is a combination of constructor stealing and prototype chaining.

Description

In combination inheritance, prototype chaining inherits properties and methods from a prototype, and constructor stealing inherits instances. In this way, we can reuse methods on prototypes by allowing methods to have their own properties. Here is an example:

functionSuperType(name) {
  this.name = name;
  this.colors = ['yellow', 'purple', 'indigo'];
}
SuperType.prototype.sayName = function() {
  //console.log(this.name);
};
functionSubType(name, age) {
  //inherit properties
  SuperType.call(this, name);
  this.age = age;
}
//inherit methods
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function() {
  //console.log(this.age);
};
varinstance1 = new SubType('John Doe', 26);
instance1.colors.push('white');
//console.log(instance1.colors); //'yellow,purple,indigo,white'
instance1.sayName(); //'John Doe';
instance1.sayAge(); //26
varinstance2 = new SubType('Kate', 21); //console.log(instance2.colors); //'yellow,purple,indigo'
instance2.sayName(); //'Kate';
instance2.sayAge(); //21

In this example, the SuperType constructor defines two properties: name and colors. The SuperType prototype has a single method called sayName(). The SubType constructor calls the SuperType constructor, passing in the name argument, and defines its own property called age. Additionally, the SubType prototype is assigned to be an instance of SuperType, and then, a new method called sayAge() is defined. With this code, it's then possible to create two separate instances of SubType that have their own properties, including the colors property, but all use the same methods. Addressing the downsides of both prototype chaining and constructor stealing, combination inheritance is the most frequently used inheritance pattern in JavaScript. It also preserves the behavior of instanceof and isPrototypeOf() to identify the composition of objects.

Prototypal inheritance

In prototypal inheritance, we use an object as a base for another object.

Description

In prototypal inheritance, there are no classes, only objects. To create an object, you can either create a totally new object or you can clone an existing object. New objects can be then extended with new properties.

Here is an example:

varobject=Object.create(null);

The preceding object has no prototype and is a clone of null:

var rectangle = {
  area: function () {
    returnthis.width * this.height;
  }
};

varrect = Object.create(rectangle);

In the preceding example, rect inherits the area function from rectangle. Here, rectangle is an object literal, an object literal is a way to create a clone of Object.prototype.

It can also be written as follows:

var rectangle = Object.create(Object.prototype);

rectangle.area = function () {
  returnthis.width * this.height;
};

We can extend the newly created object as follows:

rect.width=50;
rect.height=100;
console.log(rect.area());

We can create a constructor function that will clone rectangle for us and will extend it with the height and width properties:

var rectangle = {
  create: function (width, height) {
    var self = Object.create(this);
    self.height = height;
    self.width = width;
    return self;
  },
  area: function () {
    returnthis.width * this.height;
  }
};

varrect = rectangle.create(50, 100);

console.log(rect.area());

Parasitic inheritance

Parasitic inheritance is similar to prototypal inheritance.

Description

It simply works by creating a function that performs inheritance, object augmentation, and finally, it returns the object after completing each task:

Function abc(x) {
  Var clone=obj(abc);
  Clone.sayHi=function() {
  }; 
  return clone;
}

Var student= {
  Name="Ali";
};
Varstd=new abc(student);
Std.sayHi();

Here, in this example, we have the abc() function that has one argument, which is an object based on a new object. This object is passed to the object function and saves the resulting object into a clone variable. Now, the clone object will have a new object property, and at the end, we return the object.

Parasitic combination inheritance

A parasite is defined as an organism that lives inside another organism and relies on its resources. Similarly, in this inheritance, a child object relies on a parent object and extends its properties from it.

Description

The first constructor calls the subtype prototype and then it calls the subtype constructor. This is a very efficient way of creating new objects in JavaScript. At the end, the subtype will have all the properties of the super type. Here is an example:

function super(name) {
  this.name=["Ali"];
}
super.prototype.sayHi=function() {
  console.log("something");
}

function sub(age) {
  this.age=age;
  super.call(this,name);
}
sub.prototype=new super();
sub.prototype.sayHi();

The only difference between parasitic combination inheritance and combination inheritance is that, in the former one, the base constructor is called once, and in the latter one, the base constructor is called twice.

Subclasses

In every programming language, every subclass has a super class that inherits its properties and methods from. JavaScript is not a pure class-based programming language, but it follows some of the rules of OOP. We make classes in JavaScript using object notations.

In JavaScript, you can only perform inheritance using the constructor function or prototype. This inheritance is only done at run time, which means dynamically. Here is an example:

// super class
functionsuperClass() {
  this.bye = superBye;    //method 1
  this.hello = superHello;    //method 2
}

//sub class
functionsubClass() {
  this.inheritFrom = superClass;    //inherit-from method defines superclass
  this.inheritFrom();               //inherit from method called
  this.bye = subBye;               method 1 overridden in subclass
}

functionsuperHello() {
  return "Hello from superClass";
}

functionsuperBye() {
  return "Bye from superClass";
}

functionsubBye() {
  return "Bye from subClass";
}

To run the preceding code execute following method:

functionprintSub() {
  varnewClass = new subClass();
  console.log(newClass.bye());
  console.log(newClass.hello());
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.231