JavaScript 继承

2025-07-01  本文已影响0人  sunflower_07

JavaScript 继承

JavaScript 继承是经常被深入考察的话题,以下是一些常见的问题:

基础概念问题

  1. JavaScript 中有哪些实现继承的方式?
  1. 原型链继承的优缺点是什么?
  1. 构造函数继承的优缺点是什么?

深入技术问题

  1. 组合继承有什么问题?如何优化?
  1. 寄生组合式继承为什么是最佳实践?
  1. ES6 Class 继承和 ES5 继承有什么区别?

代码实现问题

  1. 手写一个寄生组合式继承的实现

function inheritPrototype(subType, superType) {

  const prototype = Object.create(superType.prototype);

  prototype.constructor = subType;

  subType.prototype = prototype;

}

function SuperType(name) {

  this.name = name;

}

function SubType(name, age) {

  SuperType.call(this, name);

  this.age = age;

}

inheritPrototype(SubType, SuperType);

  1. 解释下面代码的输出结果

function Parent() {

  this.name = 'parent';

}

Parent.prototype.sayName = function() {

  console.log(this.name);

};

function Child() {

  this.name = 'child';

}

Child.prototype = new Parent();

const child = new Child();

child.sayName(); // 输出什么?为什么?

实际应用问题

  1. 如何实现多重继承?
  1. 在大型项目中,你会选择哪种继承方式?为什么?

    • 通常会选择 ES6 Class 继承,因为语法清晰,易于维护

    • 如果需要更精细控制,可能会选择组合继承或寄生组合式继承

  2. 如何判断一个对象是否是另一个对象的原型?

    • 使用 Object.prototype.isPrototypeOf()

    • instanceof 操作符

准备这些问题时,最好能够结合实际代码示例来解释,展示你对 JavaScript 继承机制的深入理解。

function Parent() {

this.name = 'parent';

}

Parent.prototype.sayName = function() {

console.log(this.name);

};

function Child() {

this.name = 'child';

}

Child.prototype = new Parent();

const child = new Child();

child.sayName(); // 输出什么?为什么?

这段代码的输出结果是:

"child"

代码解析:

  1. Parent 构造函数
  1. Child 构造函数
  1. const child = new Child()
  1. child.sayName()

关键点:

如果修改代码:


Child.prototype = Parent.prototype; // 直接继承 Parent.prototype,而不是 new Parent()

const child = new Child();

child.sayName(); // 仍然输出 "child"

总结:

上一篇 下一篇

猜你喜欢

热点阅读