话不多说先上图
可以看出主要分为两类
- 原型链继承(Prototype Chain Inheritance):通过将子类的原型对象指向父类的实例来实现继承。
function Parent() {
// 父类的属性和方法
}
function Child() {
// 子类的属性和方法
}
Child.prototype = new Parent(); // 子类的原型指向父类的实例
var childInstance = new Child();
2.构造函数继承(Constructor Inheritance):使用父类的构造函数来初始化子类的属性,通过call()或apply()方法在子类的构造函数中调用父类的构造函数。
function Parent() {
// 父类的属性和方法
}
function Child() {
Parent.call(this); // 在子类构造函数中调用父类的构造函数
// 子类的属性和方法
}
var childInstance = new Child();
3.组合继承(Combination Inheritance):结合原型链继承和构造函数继承,既继承了父类原型上的方法,又能在子类的实例中拥有独立的属性
function Parent() {
// 父类的属性和方法
}
function Child() {
Parent.call(this); // 在子类构造函数中调用父类的构造函数
// 子类的属性和方法
}
Child.prototype = Object.create(Parent.prototype); // 子类的原型继承自父类的原型
Child.prototype.constructor = Child; // 修正子类原型的构造函数
var childInstance = new Child();
4.寄生式继承
使用原型式继承可以获得一份目标对象的浅拷贝,然后利用这个浅拷贝的能力再进行增强,添加一些方法,这样的继承方式就叫作寄生式继承。
5.寄生组合式继承
寄生组合式继承(Parasitic Combination Inheritance)是一种优化的继承方式,它结合了组合继承和借用构造函数的特性,避免了组合继承中调用两次父类构造函数的问题。通过借用构造函数来继承父类的属性,并使用原型链来继承父类的方法,从而实现了高效的继承关系。
下面是使用寄生组合式继承的示例代码:
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHello = function() {
console.log("Hello, my name is " + this.name);
}
function Child(name, age) {
Parent.call(this, name); // 借用构造函数继承父类的属性
this.age = age;
}
// 使用Object.create()创建一个新对象,将父类的原型赋值给它
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修正子类原型的构造函数
Child.prototype.sayAge = function() {
console.log("I am " + this.age + " years old");
}
var childInstance = new Child("Alice", 10);
childInstance.sayHello(); // Hello, my name is Alice
childInstance.sayAge(); // I am 10 years old