Preface
JS is an object-oriented weakly typed language, and inheritance is also very powerful. One of the characteristics. So how to implement inheritance in JS? let us wait and see.
Since we want to implement inheritance, we must first have a parent class. The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Core: Use the instance of the parent class as the prototype of the subclass
1 2 3 4 5 6 7 8 9 10 11 |
|
Features:
A very pure inheritance relationship, the instance is the child An instance of a class is also an instance of the parent class
The parent class adds a new prototype method/prototype attribute, and all subclasses can access it
Simple , easy to implement
Disadvantages:
If you want to add attributes and methods to a subclass, you must add them in new
Animal()
Such statements are executed later and cannot be placed in the constructor
Multiple inheritance cannot be achieved
From the prototype object Reference attributes are shared by all instances (see appendix code for details: Example 1)
When creating a subclass instance, parameters cannot be passed to the parent class constructor
Recommendation index: ★★ (two fatal flaws of 3 and 4)
Core: Use the constructor of the parent class to Enhancing subclass instances is equivalent to copying the instance attributes of the parent class to the subclass (no prototype is used)
1 2 3 4 5 6 7 8 9 10 |
|
Features:
Solved 1, subclass The problem of instances sharing parent class reference attributes
When creating a subclass instance, you can pass parameters to the parent class
Multiple inheritance can be achieved (call Multiple parent class objects)
Disadvantages:
The instance is not an instance of the parent class, but an instance of the subclass
Can only inherit the instance properties and methods of the parent class, not the prototype properties/methods
Function reuse cannot be achieved, each subclass has a parent class instance Copies of functions affect performance
Recommendation index:★★(disadvantage 3)
Core:Add new features to the parent class instance and return it as a subclass instance
1 2 3 4 5 6 7 8 9 10 11 |
|
Features:
不限制调用方式,不管是new
子类()
还是子类()
,返回的对象具有相同的效果
缺点:
实例是父类的实例,不是子类的实例
不支持多继承
推荐指数:★★
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
特点:
支持多继承
缺点:
效率较低,内存占用高(因为要拷贝父类的属性)
无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到)
推荐指数:★(缺点1)
核心:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
1 2 3 4 5 6 7 8 9 10 11 |
|
特点:
弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法
既是子类的实例,也是父类的实例
不存在引用属性共享问题
可传参
函数可复用
缺点:
调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)
推荐指数:★★★★(仅仅多消耗了一点内存)
核心:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性,避免的组合继承的缺点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
特点:
堪称完美
缺点:
实现较为复杂
推荐指数:★★★★(实现复杂,扣掉一颗星)
示例一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
The above is the detailed content of js inheritance implementation. For more information, please follow other related articles on the PHP Chinese website!