- 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();
- Java 開發從入門到精通(第2版)
- 高級語言程序設計(C語言版):基于計算思維能力培養
- Bootstrap 4 Cookbook
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- R數據科學實戰:工具詳解與案例分析
- Beginning C++ Game Programming
- Qt 4開發實踐
- Building Business Websites with Squarespace 7(Second Edition)
- Mastering SciPy
- Implementing Microsoft Dynamics NAV(Third Edition)
- Isomorphic Go
- 絕密原型檔案:看看專業產品經理的原型是什么樣
- Java核心技術速學版(第3版)
- jQuery Essentials
- Python程序員面試算法寶典