【发布时间】:2015-07-02 00:44:06
【问题描述】:
首先我应该指出,我是 JS 和 node.js 的新手。我正在尝试编写一个 node.js 聊天机器人,目前正在使用命令。
我的问题是调用方法的方法.. 如果可能的话。 这是相关部分:
var text; // received message from user
var userId; // Id of the user, number.
if (cmd.hasOwnProperty(text.split(' ')[0])) { // Message will be a string, it should be ignore if the first word is not a command name.
console.log("[Inc]" + userId + ": " + text)
if (text.split(' ').length === 1) { // If the command name is not followed by any arguments then the only argument passed should be the userID(used to send replies to the user).
cmd[text.split(' ')[0]](userId)
} else {
var args = [] // Placing all args in an array because the commands will take different number of arguments, a calculator command for example could take a lot of args.
for (var i = 1; i < text.split(' ').length; i++) {
args.push(text.split(' ')[i])
}
console.log(args)
cmd[text.split(' ')[0]](userId, args)
}
} else {
console.log("Command not found, try again");
}
var cmd = {
help : function () {
cookies : function () { //
console.log('Cookies recipe')
}
if (arguments.length === 1) {
console.log('General help text');
} else if (help.hasOwnProperty(arguments[1])) {
this[arguments[0]](); // Seems my problem was here, this was creating the reference error.
} else {
console.log('Requested topic not found')
}
},
invite : function(id) {
send_PRIVGRP_INVITE(id)
}
}
任何想法我可以如何使这项工作,或者有更好的方法,更清洁的方法来做到这一点。另外我应该提到我选择使用命令作为对象和方法,因为有些命令会更复杂,我打算给他们他们的 on file.js 并将其导出到 main.js 文件,这样添加起来会容易得多无需编辑主文件的命令。
请记住,我对此很陌生,详细的解释将有很长的路要走,谢谢。
【问题讨论】:
-
注释为“我的第一个问题在这里...”的行并没有按照您的想法进行。你不能像这样组合函数和对象定义。 (它不会抛出语法错误只是因为完全巧合这是有效的语法,但与您的预期完全不同。)
-
嗯,它会按照我的意图去做,但不是什么时候,那是我的问题 :)
-
@Trax 肯定不是;你有一个带有块的标签。你没有“呼叫”任何东西。
-
对 --
cookies是一个标签,但您的行为就像您期望它在此处采用 JSON 样式表示法一样。你在一个函数的中间。cookies应该怎么称呼? -
如果你想有条件地调用一些东西,然后将它包装在一个条件中,就像你已经在你的标记代码块之后完成了代码一样。
标签: javascript node.js