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

Node.js中如何在一个方法内调用另一个类原型方法?

解决Node.js类方法间调用的问题

嘿,我看到你在给fork的Node.js应用改代码时,卡在了类方法互相调用的环节,这其实是新手常遇到的小误区,咱们来快速搞定它~

问题根源

你现在用MessageBot.prototype.callSos(somenumbervar)直接调用原型方法,这种方式不会把当前的MessageBot实例绑定给callSos里的this,导致callSos中访问self.cache时会因为上下文错误出问题。

正确的调用方式

你已经在librarySearch里做了很棒的一步:var self = this;,这是为了避免this指向混乱,那直接用这个self来调用callSos就可以了,它会自动绑定当前实例的上下文。

修改后的完整代码如下:

'use strict'; 

/* 
* initialize the class 
*/ 
function MessageBot(bot, user, cache) { 
  this.bot = bot; 
  this.user = user; 
  this.cache = cache; 
} 

/* 
* perform commands 
*/ 
MessageBot.prototype.librarySearch = function(searchText) { 
  var self = this; 
  // 改成用self调用,绑定当前实例的上下文
  self.callSos(somenumbervar); 
} 

MessageBot.prototype.callSos = function(number) { 
  // do something else here 
  var self = this; 
  var commandList = self.cache.get('commandList'); 
} 

额外优化小建议

如果你的Node.js版本支持ES6类语法,也可以把老式构造函数改成类的写法,代码会更清晰易读:

'use strict';

class MessageBot {
  constructor(bot, user, cache) {
    this.bot = bot;
    this.user = user;
    this.cache = cache;
  }

  librarySearch(searchText) {
    this.callSos(somenumbervar);
  }

  callSos(number) {
    const commandList = this.cache.get('commandList');
  }
}

这种写法里,方法间直接用this调用即可,上下文绑定更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:19:08