在javascript中,子类原型方法安全调用父类同名方法需显式通过parent.prototype.method.call(this)实现,避免递归、确保this指向,并修复constructor;es6 class中应优先使用super.method()。

在 JavaScript 中,子类原型方法里安全调用父类同名方法,关键在于**避免无限递归、明确委托路径、保持 this 指向正确**。原生原型链本身不提供 super 机制,所以必须显式通过父类原型对象调用,并绑定当前实例。
用 Parent.prototype.methodName.call(this, ...) 显式调用
这是 ES5 环境下最通用、最安全的方式。它绕过子类自身方法,直接在父类原型上执行,并确保 this 指向当前子类实例(而非父类实例)。
- 写法:
Parent.prototype.sayHello.call(this, arg1, arg2) - 必须写全路径:
Parent.prototype,不能简写为this.constructor.prototype(子类 constructor 可能被改写,或指向错误构造器) - 必须手动传参,且需用
.call(this, ...)或.apply(this, [...])绑定上下文 - 例子:
function Animal(name) { this.name = name; }<br>Animal.prototype.speak = function() { return this.name + ' makes a sound'; };<br><br>function Dog(name, breed) { Animal.call(this, name); this.breed = breed; }<br>Dog.prototype = Object.create(Animal.prototype);<br>Dog.prototype.constructor = Dog;<br><br>Dog.prototype.speak = function() {<br> // 安全复用父类逻辑<br> const base = Animal.prototype.speak.call(this);<br> return base + ', especially ' + this.breed + ' dogs!';<br>};
注意 constructor 指向,避免原型链断裂
若子类原型直接赋值为 new Parent() 或未重置 constructor,Child.prototype.constructor 可能指向 Parent,导致 this.constructor.prototype 错误引用,进而调用失败或递归。
Java JDK 25 来自 OpenJDK 官方归档,版本为 JDK 25,本条下载地址已指向官方 Windows x64 zip 安装包直链,适合调试旧项目或兼容旧版 Java 运行环境。
- 务必在设置原型后修复:
Child.prototype.constructor = Child - 更推荐用
Object.create(Parent.prototype)初始化子类原型,它不执行父类构造函数,也天然避免污染 - 不要依赖
this.__proto__.constructor.prototype——__proto__非标准,且在严格模式或某些环境可能不可用
ES6 class 中用 super.methodName() 更简洁可靠
如果项目支持 ES6+,应优先使用 class 语法。此时 super 是语言级关键字,专为此场景设计:
- 只能在子类方法内部使用,且仅限于已定义在父类原型或父类 constructor 中的方法
- 自动绑定 this 到当前子类实例,无需手动 call/apply
- 无法赋值、解构或存储为变量;写成
const s = super会报错 - 示例:
class Animal {<br> constructor(name) { this.name = name; }<br> speak() { return this.name + ' makes a sound'; }<br>}<br><br>class Dog extends Animal {<br> constructor(name, breed) {<br> super(name); // 调用父类构造函数<br> this.breed = breed;<br> }<br> speak() {<br> return super.speak() + ', especially ' + this.breed + ' dogs!';<br> }<br>}
不推荐的危险做法
以下方式看似方便,但容易出错,应主动规避:
-
this.__proto__.__proto__.methodName():依赖非标准属性,层级易错,且 this 指向丢失 -
Parent.prototype.methodName()不带 call:this 指向变为 undefined(严格模式)或全局对象,导致逻辑异常 - 在箭头函数中用 super:箭头函数没有自己的 this 和 super,会报 ReferenceError
- 把 super 赋给变量再调用:语法非法,直接抛错
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










