返回

js实现继承方式的详细解析

前端

JavaScript 继承:六种实现方式剖析

在 JavaScript 中,继承是对象获取其他对象属性和方法的能力。这对于代码复用和维护至关重要。JavaScript 提供了多种继承方式,每种方式都有其优点和缺点。

原型链继承

这是最基本的继承方式。对象通过一个内部的 [[Prototype]] 属性链接到其原型对象,从而可以访问原型对象的属性和方法。

function Parent() {
  this.name = 'parent';
}

Parent.prototype.play = function() {
  console.log(this.name + ' is playing.');
}

function Child() {}

Child.prototype = new Parent();

const s1 = new Child();
s1.play(); // "parent is playing"

构造函数继承

子类的构造函数调用父类的构造函数来获得父类的属性和方法。

function Parent(name) {
  this.name = name;
}

Parent.prototype.play = function() {
  console.log(this.name + ' is playing.');
}

function Child(name) {
  Parent.call(this, name);
}

const s1 = new Child('child');
s1.play(); // "child is playing"

组合继承

这种方式结合了原型链继承和构造函数继承,解决了这两种方式的缺点。

function Parent(name) {
  this.name = name;
}

Parent.prototype.play = function() {
  console.log(this.name + ' is playing.');
}

function Child(name) {
  Parent.call(this, name);
  this.age = 10;
}

Child.prototype = new Parent();

const s1 = new Child('child');
s1.play(); // "child is playing"
console.log(s1.age); // 10

原型式继承

创建一个新对象,并将其原型设置为另一个对象来实现继承。

const parent = {
  name: 'parent',
  play() {
    console.log(this.name + ' is playing.');
  }
};

const child = Object.create(parent);
child.name = 'child';

child.play(); // "child is playing"

寄生式继承

创建一个新对象,并将其属性和方法复制到另一个对象来实现继承。

function Parent(name) {
  this.name = name;
}

Parent.prototype.play = function() {
  console.log(this.name + ' is playing.');
}

function Child(name) {
  const parent = new Parent(name);
  return Object.assign({}, parent, {
    name: name
  });
}

const s1 = new Child('child');
s1.play(); // "child is playing"

混入式继承

将一个对象的属性和方法复制到另一个对象来实现继承。

const parent = {
  name: 'parent',
  play() {
    console.log(this.name + ' is playing.');
  }
};

const child = Object.assign({}, parent, {
  name: 'child'
});

child.play(); // "child is playing"

结论

JavaScript 提供了多种继承方式,选择合适的继承方式取决于实际需求。原型链继承最简单,而组合继承是最灵活、最推荐的方式。

常见问题解答

  • 哪种继承方式最好?

    • 组合继承通常是最佳选择,因为它解决了原型链继承和构造函数继承的缺点。
  • 如何检查继承关系?

    • 使用 instanceof 运算符,例如 instanceof Parent
  • 原型链可以被修改吗?

    • 可以,但谨慎修改,因为这可能会导致意外行为。
  • 什么是委托?

    • 委托是一种替代继承的机制,其中对象将方法委托给另一个对象。
  • 混入式继承和寄生式继承有什么区别?

    • 寄生式继承创建一个新对象,而混入式继承修改现有对象。