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

JavaScript原型继承中getDetails方法输出内容重复问题求助

问题分析与解决

问题根源

在Teacher.prototype.getDetails方法中,你使用this.__proto__.getDetails()尝试调用父类(Person)的方法,但this.__proto__指向的是Teacher.prototype,而Teacher.prototype自身已经重写了getDetails方法,这会导致递归调用当前的Teacher.getDetails方法,最终造成"main subject is Physics"重复输出。

解决方法

要正确调用Person原型上的原始方法,需要明确指向Person.prototype,并通过call(this)绑定当前实例的上下文(保证this指向teacher1实例,符合原型链的调用逻辑)。

修改后的完整代码

function Person() {
  throw new Error("The person is abstract constructor function");
}

Person.prototype.personName = "John";
Person.prototype.age = 21;
Person.prototype.getDetails = function() {
  return `Person name ${this.personName} and age is ${this.age}.`;
};

function Teacher() {}

Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.mainSubject = "Physics";
Teacher.prototype.getDetails = function() {
  // 调用Person原型的getDetails方法,并绑定当前实例的this
  return `${Person.prototype.getDetails.call(this)} main subject is ${this.mainSubject}.`;
};

var teacher1 = new Teacher();
console.log(teacher1.getDetails());

更灵活的写法(避免硬编码Person)

如果不想直接写死Person,可以通过Object.getPrototypeOf获取Teacher原型的父原型(即Person.prototype):

Teacher.prototype.getDetails = function() {
  const parentPrototype = Object.getPrototypeOf(this.constructor.prototype);
  return `${parentPrototype.getDetails.call(this)} main subject is ${this.mainSubject}.`;
};

输出结果

修改后调用teacher1.getDetails()会得到预期输出:

Person name John and age is 21. main subject is Physics.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:00:23