You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过构造函数构建JavaScript原型链实现继承?

实现原型链继承让方法通过原型查找

首先要调整Person的结构,把共享方法放到原型上,再给Student搭建正确的原型链:

1. 重构Person构造函数

把hello方法移到Person的原型上,让所有实例共享这个方法,避免每个实例都创建重复的函数:

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

// 将hello方法挂载到Person的原型
Person.prototype.hello = function () {
  return "It's a-me, " + this.name + "!";
};

2. 搭建Student的原型链

有两种常用的优雅实现方式:

方式一:基于ES5的原型链设置

function Student(name) {
  // 调用Person构造函数,继承实例属性name
  Person.call(this, name);
  // 新增Student独有的实例属性
  this.books = [];
}

// 创建以Person.prototype为原型的对象,作为Student的原型
Student.prototype = Object.create(Person.prototype);
// 修正原型的constructor指向,避免默认指向Person
Student.prototype.constructor = Student;

方式二:使用ES6 class语法(更简洁直观)

如果项目支持ES6及以上,class语法是原型链的语法糖,写法更清晰:

class Person {
  constructor(name) {
    this.name = name;
  }

  hello() {
    return "It's a-me, " + this.name + "!";
  }
}

class Student extends Person {
  constructor(name) {
    super(name); // 调用父类构造函数继承name属性
    this.books = [];
  }
}

验证效果

执行测试代码:

const mario = new Student("mario");
console.log(mario.name); // "mario"
console.log(mario.hello()); // "It's a-me, mario!"
console.log(mario.books); // []
// 检查hello是否来自原型链
console.log(mario.hasOwnProperty('hello')); // false,说明是通过原型链查找的

这样修改后,hello方法会通过原型链从Person的原型上获取,不会挂载到每个Student实例上,同时Student和Person的代码同步性更好,后续修改Person的原型方法时,Student实例会自动生效,无需手动维护重复代码。

内容的提问来源于stack exchange,提问作者Him

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:25:22