官术网_书友最值得收藏!

  • Expert Angular
  • Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
  • 238字
  • 2021-07-15 17:05:32

Inheritance

Inheritance is the concept of inheriting behaviors from another class or object. It helps to achieve code reusability and build a hierarchy in relationships of classes or objects. Also, inheritance helps you to cast similar classes.

JavaScript, by targeting ES5, doesn't support classes, and so class inheritance is impossible to implement. However, we can implement prototype inheritance instead of class inheritance. Let's explore inheritance in ES5 with examples.

First, create a function named Animal as follows:

var Animal = function() { 
  
    this.sleep = function() { 
       console.log('sleeping'); 
   } 
  
    this.eat = function() { 
       console.log('eating'); 
   } 
} 

Here, we created a function named Animal with two methods: sleep and eat. Now, let's extend this Animal function using the prototype as follows:

Animal.prototype.bark = function() { 
    console.log('barking'); 
} 

Now, we can create an instance of Animal and call the extended function, bark, as follows:

var a = new Animal(); 
a.bark(); 

We can use the Object.Create method to clone a prototype of the parent and create a child object. Then, we can extend the child object by adding methods. Let's create an object named Dog and inherit it from Animal:

var Dog = function() { 
    this.bark = new function() { 
       console.log('barking'); 
   } 
} 

Now, let's clone the prototype of Animal and inherit all the behavior in the Dog function. Then, we can call the Animal method using the Dog instance, as follows:

Dog.prototype = Object.create(animal.prototype); 
var d = new Dog(); 
d.sleep(); 
d.eat(); 
主站蜘蛛池模板: 中卫市| 邓州市| 甘泉县| 龙江县| 晋江市| 那曲县| 镇安县| 威信县| 繁昌县| 靖宇县| 柏乡县| 稻城县| 阜阳市| 东光县| 兴仁县| 诸城市| 正定县| 东兰县| 曲沃县| 龙州县| 抚宁县| 庆安县| 钦州市| 尖扎县| 威海市| 绥江县| 冀州市| 铁力市| 台湾省| 印江| 乌海市| 邵武市| 汝城县| 叙永县| 延安市| 察雅县| 红原县| 新丰县| 通山县| 惠安县| 肃北|