在JavaScript中,继承有以下几种方式:
- 原型链继承
原型链继承是利用原型链来实现的,实现方式如下:
function Parent() {
this.name = "parent";
}
Parent.prototype.getName = function() {
return this.name;
}
function Child() {
this.age = 18;
}
Child.prototype = new Parent();
const child = new Child();
console.log(child.getName()); // 输出:parent
- 构造函数继承
构造函数继承是通过在子类构造函数中调用父类构造函数来实现的,实现方式如下:
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
const child = new Child("child", 18);
console.log(child.getName()); // 报错:child.getName is not a function
- 组合继承
组合继承是将原型链继承和构造函数继承结合起来,实现方式如下:
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function() {
return this.name;
}
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child("child", 18);
console.log(child.getName()); // 输出:child
- 原型式继承
原型式继承是通过复制一个对象来实现继承,实现方式如下:
const parent = {
name: "parent",
getName: function() {
return this.name;
}
}
const child = Object.create(parent, {
age: {
value: 18
}
});
console.log(child.getName()); // 输出:parent
- 寄生式继承
寄生式继承是在原型式继承的基础上添加一个包装函数,实现方式如下:
const parent = {
name: "parent",
getName: function() {
return this.name;
}
}
function createChild(parent, age) {
const child = Object.create(parent, {
age: {
value: age
}
});
child.getName = function() {
return `${parent.getName()} ${this.age}`;
}
return child;
}
const child = createChild(parent, 18);
console.log(child.getName()); // 输出:parent 18