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

JavaScript原型继承问题:调用CheckingAccount.balance报类型错误

问题分析与解决方案

首先咱们先拆解你代码里的核心问题:
你错误地把balance当成了构造函数CheckingAccount的静态方法来调用(CheckingAccount.balance()),但实际上你是把balance定义在Account.prototype上的——这是给实例对象用的方法,不是给构造函数本身用的。除此之外,你的继承逻辑还有两处可以完善的地方,咱们一步步来改:

1. 修复核心错误:用实例调用原型方法

原型上的方法是给通过new创建的实例用的,不是给构造函数本身用的。你应该用你已经创建的checking实例来调用balance,而不是直接调用构造函数:

// 错误的调用方式
// CheckingAccount.balance();

// 正确的调用方式
checking.balance(); // 会输出 "This is the balance"

2. 完善继承逻辑:调用父类构造函数 + 重置constructor

当前你的CheckingAccount实例没法获取Account里的firstName和lastName,因为你没在CheckingAccount的构造函数里调用父类的构造函数。另外,用Object.create(Account.prototype)覆盖原型后,CheckingAccount.prototype.constructor会指向Account,这可能会影响后续的类型判断,所以需要手动重置。

修正后的完整代码:

function Account(fName, lName) {
  this.firstName = fName;
  this.lastName = lName;
}

Account.prototype.balance = function() {
  console.log("This is the balance");
}

function CheckingAccount(fName, lName) {
  // 调用父类构造函数,让实例继承firstName和lastName属性
  Account.call(this, fName, lName);
  this.salary = 10000;
}

// 继承父类的原型方法
CheckingAccount.prototype = Object.create(Account.prototype);
// 重置constructor指向,避免后续类型判断出错
CheckingAccount.prototype.constructor = CheckingAccount;

// 创建实例
let account = new Account("John", "Doe");
let checking = new CheckingAccount("Jane", "Smith"); // 现在可以传入姓名参数了

// 正确调用实例方法
checking.balance(); // 输出 "This is the balance"
console.log(checking.firstName); // 输出 "Jane"

额外补充

  • 原型方法是挂载在构造函数的prototype对象上的,只有实例能访问;如果想给构造函数本身加方法(静态方法),需要直接挂载到构造函数上,比如Account.staticMethod = function() { ... },这时候才能用Account.staticMethod()调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:09:07