原型链继承2.借用构造函数继承3.组合式继承4.ES6的class类继承
时间: 2024-06-21 07:02:46 浏览: 157
原型链继承(Prototype Inheritance)在JavaScript中是通过创建一个新对象并让它引用另一个对象的原型来实现的。例如:
```javascript
function Parent() {}
Parent.prototype.method = function() {
console.log('Parent method');
};
let child = new Parent();
child.method(); // 输出: "Parent method"
```
**借用构造函数继承**(Constructo r Chaining)利用已有构造函数作为父类,通过`new`关键字传递给子类实例化过程,间接实现了继承:
```javascript
function Parent() {
this.parentProp = 'parent';
}
function Child() {
Parent.call(this); // 借用父类构造函数
this.childProp = 'child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
let childInstance = new Child();
console.log(childInstance.parentProp); // 输出: "parent"
console.log(childInstance.childProp); // 输出: "child"
```
**组合式继承**(Mix-in or Prototype Mixing)结合原型链和构造函数继承,允许从多个源继承属性和方法:
```javascript
function Mixin(target) {
for (let prop in Mixin.prototype) {
target[prop] = Mixin.prototype[prop];
}
}
function Parent() {
this.parentProp = 'parent';
}
Mixin(Parent.prototype);
let child = new Parent();
console.log(child.parentProp); // 输出: "parent"
```
**ES6的class类继承**(Class-based Inheritance)使用`extends`关键字实现:
```javascript
class Parent {
constructor() {
this.parentProp = 'parent';
}
parentMethod() {
console.log('Parent method');
}
}
class Child extends Parent {
constructor() {
super();
this.childProp = 'child';
}
childMethod() {
console.log('Child method');
}
}
let childInstance = new Child();
childInstance.parentMethod(); // 输出: "Parent method"
childInstance.childMethod(); // 输出: "Child method"
```
阅读全文