'TypeError: is not a function' instance method in Node.js

问题描述 投票:0回答:1

我收到错误消息:

TypeError: Account.getAccount 不是函数 ...

当我从我创建的类中调用实例方法时。具有相同导入的其他脚本可以毫无问题地调用构造函数或实例字段,所以我不知道为什么实例方法失败。我查看了所有文档,但无法找出问题所在。这是在 replit 上运行的。

此文件

account.js
包含类 Account 和两个实例方法,
getAccount
payAccount
.

class Account {
  static lastId = 1001;
  static generateId() {
    return Account.lastId++;
  }
  static accounts = [1000];
  static names = [];
  static ids = [];
  profile;
  ign;
  balance;
  id;
  constructor(ign, profile) {
    this.ign = ign;
    this.profile = profile;
    this.balance = 0;
    this.id = Account.generateId();
    Account.accounts.push(this);
    Account.names.push(ign);
    Account.ids.push(this.id);
  }
  getAccount(id) { // this is the instance method that is called later.
    for (const element of accounts) {
      if (id == element.id) return element;
    }
    return;
  }
  payAccount(account, amount) {
    account.balance += amount;
  }
}
module.exports = Account;

这里是另一个文件 pay.js 的片段(完整路径命令/pay.js):

const { SlashCommandBuilder } = require('discord.js');
const Account = require('../Account') // it is in a folder, hence the '../'
module.exports = {
  data: new SlashCommandBuilder()
    .setName('pay')
    .setDescription('Description')
    .addIntegerOption(fromAccount =>
      fromAccount.setName('from_account')
        .setDescription('One of your Accounts.')
        .setRequired(true)),
async execute(interaction) {
    let fromId = interaction.options.getInteger('from_account');
    let fromAccount = Account.getAccount(fromId); // the error is thrown here
  }
}

我做错了什么?我见过关于普通函数的类似问题,但语法与类不同。 (另外请忽略我只是想使用实例方法绕过这么多静态数组。)

javascript node.js discord discord.js
1个回答
1
投票

需要实例化一个

Account
实例来调用类的方法:

async execute(interaction) {
    let fromId = interaction.options.getInteger('from_account');
    const account = new Account(<ign>, <profile>);
    let fromAccount = account.getAccount(fromId);
  }

或者,将方法声明为

static

static getAccount(id) { // this is the instance method that is called later.
    for (const element of accounts) {
      if (id == element.id) return element;
    }
    return;
}

...

let fromAccount = Account.getAccount(fromId); // will work

最后,您可以将

getAccount
实现更改为:

static getAccount(id) { 
    return Account.accounts.find(a => a.id === id);
}
© www.soinside.com 2019 - 2024. All rights reserved.