JavaScript中的继承可以通过原型链和类的方式实现。
原型链继承: 原型链继承是JavaScript中最基本的继承方式,通过将父类的实例作为子类的原型,实现属性和方法的继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {
this.age = 10;
}
Child.prototype = new Parent();
var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'
通过将Child的原型指向Parent的实例,Child就可以继承Parent的属性和方法。
构造函数继承: 构造函数继承是通过在子类的构造函数中调用父类的构造函数,实现属性的继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {
Parent.call(this);
this.age = 10;
}
var child = new Child();
child.sayHello(); // 报错,sayHello不是继承自Parent的
console.log(child.name); // 输出 'Parent'
使用Parent.call(this)可以在子类构造函数中调用父类构造函数,从而继承父类的属性。
组合继承: 组合继承是将原型链继承和构造函数继承结合起来,通过分别调用父类构造函数和设置子类原型实现属性和方法的继承。
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {
Parent.call(this);
this.age = 10;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'
使用Parent.call(this)继承父类的属性,使用Child.prototype = new Parent()继承父类的方法。需要注意的是,需要将子类原型的构造函数重新指向子类本身,以避免构造函数被重写。
ES6类继承: ECMAScript 6中引入了类的概念,可以通过extends关键字来实现类的继承。
class Parent {
constructor() {
this.name = 'Parent';
}
sayHello() {
console.log('Hello from Parent');
}
}
class Child extends Parent {
constructor() {
super();
this.age = 10;
}
}
var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'
使用extends关键字来继承父类,使用super关键字来调用父类的构造函数和方法。
以上是JavaScript中实现继承的几种方式,可以根据需求和场景选择适合的方式