使用 object.getprototypeof() 获取原型对象,并调用父类方法。具体做法是:在子类方法中通过 object.getprototypeof(subclass.prototype) 拿到父类原型,再调用其上的同名函数,传入当前实例(this)和额外参数即可实现覆盖与扩展。

如何获取父类原型并调用其方法
直接回答:通过 Object.getPrototypeOf(SubClass.prototype) 可以准确获取父类的原型对象,进而调用其方法。这是 ES5 及之后标准且安全的做法,避免了硬编码字符串或依赖构造函数名称。

function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayName = function() {
console.log('Hello, I am ' + this.name);
};
function Child() {
this.name = 'Child';
}
// 继承
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
// 覆盖并调用父类
Child.prototype.sayName = function() {
// 获取父类原型
var parentProto = Object.getPrototypeOf(Child.prototype);
// 调用父类方法
parentProto.sayName.call(this);
console.log('And I am a child');
};
var child = new Child();
child.sayName();
运行上述代码,控制台将输出:
Hello, I am Child
And I am a child
这里的关键在于 parentProto.sayName.call(this)。我们不仅调用了父类的方法,还通过 call 改变了 this 的指向,确保父类方法操作的是子类的实例属性(如 this.name),从而正确打印出 'Child' 而不是 'Parent'。
如果父类方法需要传递额外参数怎么办
直接回答:只需在调用父类方法时,将额外参数作为后续参数传递给 call 或 apply 即可。父类方法定义时接收的参数会按顺序被传入,不影响 this 的绑定逻辑。

FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
function Parent(msg) {
this.message = msg || 'Default';
}
Parent.prototype.showMessage = function(suffix) {
console.log(this.message + (suffix ? suffix : ''));
};
function Child(msg) {
this.message = msg || 'Child Default';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.showMessage = function(suffix, prefix) {
var parentProto = Object.getPrototypeOf(Child.prototype);
// 传递 suffix 和 prefix 给父类方法
// 注意:父类 showMessage 只接受一个 suffix 参数
// 这里演示如何将子类的多个参数适配给父类
parentProto.showMessage.call(this, suffix);
if (prefix) {
console.log('Prefix: ' + prefix);
}
};
var child = new Child('Custom Message');
child.showMessage(' - Extended', 'Hi');
运行结果:
Custom Message - Extended
Prefix: Hi
在这个例子中,Child.prototype.showMessage 接收了 suffix 和 prefix 两个参数。它选择将 suffix 传递给父类的 showMessage 方法,而 prefix 则在子类中单独处理。这种模式允许子类在不破坏父类接口的前提下,扩展功能或修改行为。
当父类方法抛出异常时如何处理
直接回答:如果父类方法在执行过程中抛出异常,该异常会向上传播到子类方法的调用栈中。因此,建议在调用父类方法时使用 try...catch 块来捕获并处理异常,以确保子类逻辑的健壮性。
function Parent() {}
Parent.prototype.riskyMethod = function() {
throw new Error('Something went wrong in Parent!');
};
function Child() {}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.safeMethod = function() {
var parentProto = Object.getPrototypeOf(Child.prototype);
try {
parentProto.riskyMethod.call(this);
} catch (e) {
console.error('Caught error from Parent:', e.message);
// 可以选择重新抛出,或者执行备用逻辑
console.log('Executing fallback logic');
}
};
var child = new Child();
child.safeMethod();
运行结果:
Caught error from Parent: Something went wrong in Parent!
Executing fallback logic
通过这种方式,即使父类方法失败,子类也能优雅地处理错误,避免整个程序崩溃。这是一种常见的防御性编程实践,特别适用于父类行为不可控或存在潜在风险的场景。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










