温馨提示×

js实现继承的方法有哪些

js
小亿
105
2023-08-04 13:33:03
栏目: 编程语言

在 JavaScript 中,有几种方法可以实现继承:

  1. 原型链继承:通过将子类的原型对象设置为父类的一个实例来实现继承。这样子类就可以继承父类的属性和方法。例如:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {}
Child.prototype = new Parent();
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
  1. 构造函数继承:通过在子类构造函数中调用父类构造函数来实现继承。这样子类就可以继承父类的属性,并且子类的每个实例都有自己的属性的副本。但是,子类无法继承父类的原型上的方法。例如:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 报错:child.sayHello is not a function
  1. 组合继承:通过同时使用原型链继承和构造函数继承来实现继承。这样子类就可以继承父类的属性和方法,并且子类的每个实例都有自己的属性的副本。例如:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'
  1. 寄生组合继承:通过创建一个中间函数来实现继承,并且在该中间函数中使用 Object.create() 方法来创建子类原型的副本,然后再将该副本设置为子类的原型。这样可以避免调用父类构造函数两次。例如:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello');
}
function Child() {
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(child.name); // 输出 'Parent'
child.sayHello(); // 输出 'Hello'

这些都是常见的实现继承的方法,每种方法都有自己的优缺点,可以根据具体情况选择合适的方法。

0