我是JS的新手,我目前正在研究一个IRC机器人。我已经制作了以下模块,我想用它来创建机器人命令。
/***
* Module contains available bot commands including
* access levels to view/utilise command and help text.
*
* Usage example: commands.tg.play(payload);
*
***/
module.exports = commands = {
tg: {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: function(payload){tg(payload);}
},
help: {
reg: '^[. - !]help',
description: 'some help text for intel',
play: function(payload){help(payload);}
}
};
function tg(payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
}
function help(payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
return console.log(output);
}
正如您所看到的,我目前正在命令对象中定义一些方法。为了尝试让事情变得更清洁,我定义了在命令对象下面实际运行的函数。我可以通过commands.help.play(payload)轻松访问这些内容。但是我想知道是否有更好的方法来做到这一点,还是我正确的方向?目前这些命令非常具有骨架性,并且将会执行更多的工作,但我只是想发布一些内容来提供一般性的想法。
答案 0 :(得分:1)
这是我个人的偏好,但我会选择这个。单例模式与构造函数
function Commands(){
this.commands = {};
this.tg = function (payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
};
this.help = function (payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
}
this.commands.tg= {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: this.tg
};
this.commands.help= {
reg: '^[. - !]help',
description: 'some help text for intel',
play: this.help
};
}
if(!!obj)
obj = new Commands();
module.exports = obj;
答案 1 :(得分:1)
我不喜欢你正在制作的额外fn电话:play:function(payload){tg(payload);}
应该只是play:tg
,因为函数是js中的一阶公民。我也更喜欢在文件末尾分配module.exports。
/***
* Module contains available bot commands including
* access levels to view/utilise command and help text.
*
* Usage example: commands.tg.play(payload);
*
***/
var commands = {};
function tg(payload){
//Example: msg_route: pm msg_from: munkee msg_data: .tg munkee testing message via tg command msg_match: .tg msg_method: .
console.log("msg_route:" + payload.msg_route + ' msg_from: ' + payload.msg_from + ' msg_data: ' + payload.msg_data + ' msg_match: ' + payload.msg_match + ' msg_method: ' + payload.msg_method);
return;
}
function help(payload){
var output='Available commands: ';
for (var i in commands){
output=output+ ' ' + i.toString();
}
return console.log(output);
}
// export
module.exports = commands = {
tg: {
reg: '^[. - !]tg',
help: 'some help text for tg',
play: tg;
},
help: {
reg: '^[. - !]help',
description: 'some help text for intel',
play: help}
}
};