js中的构造函数继承,混合继承,es6继承,请详细讲解
时间: 2024-02-25 08:54:29 浏览: 18
好的,我来详细讲解一下。
1. 构造函数继承
构造函数继承是一种通过调用父构造函数来继承父类属性和方法的方式。在子类中通过调用父类构造函数来实现继承,子类的实例会具有父类的属性和方法。具体实现方式如下:
```javascript
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
var child = new Child('Tom', 18);
console.log(child.name); // Tom
console.log(child.age); // 18
```
在上面的代码中,我们定义了一个父类 Parent 和一个子类 Child,Child 通过在构造函数中调用 Parent 来实现继承。这种方式的缺点是无法继承父类原型上的方法。
2. 混合继承
混合继承是一种通过同时使用构造函数继承和原型链继承来继承父类属性和方法的方式。在子类中既通过调用父类构造函数来继承父类属性,又通过将子类的原型指向父类的实例来继承父类原型上的方法。具体实现方式如下:
```javascript
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child('Tom', 18);
console.log(child.name); // Tom
console.log(child.age); // 18
child.sayName(); // Tom
```
在上面的代码中,我们定义了一个父类 Parent 和一个子类 Child,Child 通过同时使用构造函数继承和原型链继承来实现继承。这种方式的优点是既可以继承父类的属性,也可以继承父类原型上的方法。
3. ES6 继承
ES6 继承是一种通过使用 class 和 extends 关键字来继承父类属性和方法的方式。在子类中使用 extends 关键字继承父类,子类的实例会具有父类的属性和方法。具体实现方式如下:
```javascript
class Parent {
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
var child = new Child('Tom', 18);
console.log(child.name); // Tom
console.log(child.age); // 18
child.sayName(); // Tom
```
在上面的代码中,我们使用 class 和 extends 来定义父类 Parent 和子类 Child,Child 通过 extends 关键字继承 Parent 来实现继承。这种方式是 ES6 中推荐的继承方式,具有语法简洁、易于理解等优点。