Node.js中调用Account.getAccount报TypeError: is not a function问题
解决TypeError: Account.getAccount is not a function的问题
问题根源
你在account.js中定义的getAccount是实例方法,但在pay.js里直接通过Account类本身调用(Account.getAccount()),实例方法只能在类的实例对象上调用,不能直接通过类本身触发。
两种解决办法
1. 将方法改为静态方法
如果getAccount不需要依赖实例的属性,只是和类相关的工具方法,在account.js中给方法添加static关键字:
// account.js class Account { static getAccount() { // 你的方法逻辑 } } module.exports = Account;
修改后,pay.js里的Account.getAccount()就能正常调用。
2. 先创建实例再调用方法
如果getAccount需要用到实例的字段(比如账号余额、用户ID等实例属性),必须先实例化类再调用方法:
// pay.js const Account = require('./account.js'); // 先创建Account实例(传入构造函数所需参数) const account = new Account('user123', 1000); // 调用实例方法 account.getAccount();
额外检查点
- 确认
account.js的导出逻辑正确:需导出类本身(module.exports = Account;),而非类的实例 - 检查
pay.js的导入路径是否正确,避免导入了其他同名文件
内容的提问来源于stack exchange,提问作者Henry C
相关产品推荐
相关产品推荐

