gpt4 book ai didi

javascript - 如果方法存在则调用该方法的方法

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:02 25 4
gpt4 key购买 nike

首先我应该指出,我对 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)
}

}

有什么想法可以让这项工作成功,或者有没有更好、更干净的方法来做到这一点。另外我应该提到我选择使用命令作为对象和方法,因为有些命令会更复杂,我打算将它们提供给 file.js 并将其导出到 main.js 文件,这样添加起来会容易得多始终不编辑主文件的命令。

请记住,我对此很陌生,详细的解释会有很大帮助,谢谢。

最佳答案

我认为下面的代码给出了您正在寻找的行为,但它是相当反模式的。它看起来有点面向对象,但实际上并非如此,因为它在包含函数的每次调用中都以相同的方式定义 cookies 函数。您可能希望 cookie 存在于 cmd 上,但这不是您的问题所问的。

我认为你最终会慢慢做一些真正的面向对象的事情,你会 have a constructor set up all the properties for your functions within functions 。也就是说,您需要保留 JSON 表示法,并将其作为返回 cmd 实例的对象构造函数内的“真实代码”运行,您可以以不同的方式初始化该实例(可能使用 JSON 表示法!)。

如果这不是您想要的,请发表评论,我会修改。再说一次,我实际上不会在生产中使用这段代码。反模式。

var cmd = {
help: function () {
var context = this.help;
context.cookies = function () {
console.log('Cookies recipe');
};

if (arguments.length === 0) {
console.log('General help text');
} else if (context.hasOwnProperty(arguments[0])) {
context[arguments[0]]();
} else {
console.log('Requested topic not found');
}
},

invite: function(id) {
//send_PRIVGRP_INVITE(id);
console.log("send_PRIVGRP_INVITE(" + id + ");");
}
};

cmd.help();
cmd.help("cookies");
cmd.help("milk");
cmd.invite("wack");
cmd.help("invite");

这将产生以下输出:

General help text
Cookies recipe
Requested topic not found
send_PRIVGRP_INVITE(wack);
Requested topic not found
<小时/>

编辑:这里有一些关于如何使用this的好信息:

快速掌握的是 this 引用函数的执行上下文,如 the SO answer quotes ...

The ECMAScript Standard defines this as a keyword that "evaluates to the value of the ThisBinding of the current execution context" (§11.1.1).

因此,如果您没有附加任何内容到对象,则 window (或者您的全局上下文是什么;在浏览器中,它是 window)是 这个。除非您使用严格模式...但否则 this 是调用对象。例如,当调用 bar 时,foo.bar() 应该在 this 中包含 foo

调用函数时,您可以使用函数 callapply 显式设置 this 中的上下文。但这一切都在这些链接中进行了详细解释。

一个面向对象的解决方案

对于如何使用面向对象,我可能会做类似的事情

function Cmd(helpInfo, executableFunctions) {
var functionName;

// Note that we're no longer redefining the cookies function
// with every call of cmd.help, for instance.
this.help = function (helpTopic) {
if (undefined === helpTopic) {
console.log('General help text');
} else if (helpInfo.hasOwnProperty(helpTopic)) {
console.log(helpInfo[helpTopic]);
} else {
console.log('Requested topic not found');
}
};

for (functionName in executableFunctions)
{
if (executableFunctions.hasOwnProperty(functionName))
{
this[functionName] = executableFunctions[functionName];
}
}
}

// Set up initialization info for your new command object.
var helpInfoCooking = {
cookies: "Cookies recipe",
brownies: "Brownies recipe",
cake: "Cake receipe"
};

var executableFunctions = {
invite: function(id) {
//send_PRIVGRP_INVITE(id);
console.log("send_PRIVGRP_INVITE(" + id + ");");
},
say: function(message) {
console.log("you'd probably say \"" + message + "\" somehow");
}
};

// Create an instance of Cmd.
var cmd = new Cmd(helpInfoCooking, executableFunctions);

cmd.help();
cmd.help("cookies");
cmd.help("milk");
cmd.help("cake");
cmd.invite("wack");
cmd.help("invite");

cmd.say("This is a message");

结果:

General help text
Cookies recipe
Requested topic not found
Cake receipe
send_PRIVGRP_INVITE(wack);
Requested topic not found
you'd probably say "This is a message" somehow

YMMV 等。如果您正在进行单例设置,可能有点矫枉过正,但重新排列成真正的单例设置也不难。

关于javascript - 如果方法存在则调用该方法的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29830086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com