javaScript继承本质是操作prototype和constructor,通过原型链实现方法共享与属性继承,es6 class仅为语法糖,底层仍依赖__proto__和prototype链。

javascript继承的本质就是操作prototype和constructor
JavaScript没有类继承的语法糖之前,所有“继承”都靠手动设置对象的__proto__或修改prototype链实现。ES6的class只是语法糖,底层仍基于原型链。关键不是“怎么写class”,而是“怎么让实例能访问父级方法”。
-
Child.prototype.__proto__ = Parent.prototype是最直白的原型链连接方式(不推荐直接用__proto__) - 更安全的做法是用
Object.setPrototypeOf(Child.prototype, Parent.prototype) - 必须手动修复
Child.prototype.constructor,否则它会指向Parent而不是Child - 子类构造函数里必须显式调用
Parent.call(this, ...args),否则父类实例属性不会挂到this上
用Object.create()模拟标准原型链继承
这是最接近ES5规范的写法,避免污染原生__proto__,也兼容老环境。
function Parent(name) { this.name = name; } Parent.prototype.say = function() { return 'Hello ' + this.name; }; function Child(name, age) { Parent.call(this, name); // 继承实例属性 this.age = age; } Child.prototype = Object.create(Parent.prototype); // 建立原型链 Child.prototype.constructor = Child; // 修复constructor Child.prototype.getAge = function() { return this.age; }; const c = new Child('Alice', 12); console.log(c.say()); // 'Hello Alice' console.log(c.getAge()); // 12
class extends背后发生了什么
写class Child extends Parent时,js引擎自动做了三件事:设置Child.__proto__ === Parent(静态方法可继承)、设置Child.prototype.__proto__ === Parent.prototype(实例方法可继承)、强制子类构造函数第一行必须调用super()(否则this未定义)。
- 不调用
super()会报错:ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor -
super()不仅初始化this,还把父类实例属性挂上去;不调用就只有空this - 静态方法继承靠的是
Child.__proto__指向Parent,和实例链是两套机制
原型链断裂的典型表现和排查点
常见现象不是“报错”,而是“方法找不到”或“constructor错乱”。比如instance.constructor === Parent却期望是Child,或者instance instanceof Parent返回false。
立即学习“Java免费学习笔记(深入)”;
- 忘了重设
Child.prototype.constructor→ 导致new Child().__proto__.constructor === Parent - 用
Child.prototype = {...}完全替换原型对象 → 断开与Parent.prototype的连接 - 在
Child构造函数中漏掉Parent.call(this, ...)→ 实例缺少父类定义的属性 - 混用
class和函数构造器(比如class C extends function F(){})→ 语法错误或行为不可预测
原型链不是抽象概念,它是真实存在的__proto__指针链。每个对象都有它,每个函数都有prototype,而prototype本身是个对象,所以也有__proto__。真正容易被忽略的是:**constructor属性不是只读的,但它一旦丢失,instanceof和序列化、调试工具都会出问题**。