簡體   English   中英

調用方法的方法(如果存在)

[英]Call the method of a method if it exists

首先,我應該指出,我是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函數。 您可能希望cookies駐留在cmd ,但這不是您的問題所要問的。

我認為您最終會精打細算地做一些面向對象的工作,在這里您將有一個構造函數來設置函數中函數的所有屬性 也就是說,您將需要保留JSON表示法,並在對象構造函數中以“真實代碼”的形式運行它,以返回可以用不同方式初始化(​​可能使用JSON表示法!)的cmd實例。

如果這不是您想要的,請發表評論,我會進行修改。 同樣,我不會在生產中實際使用此代碼。 反模式。

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是指函數的執行上下文 ,因為SO答案引用了 ...

ECMAScript標准將其定義為“評估為當前執行上下文的ThisBinding的值”(第11.1.1節)的關鍵字。

因此,如果您沒有在對象, window (或任何全局上下文;在瀏覽器中是window )上附加任何內容,則為this 除非您使用嚴格模式...否則,否則this就是調用對象。 foo.bar()應該有foothis時候bar被調用,例如。

您可以使用函數call ,並apply於明確地設置這是在上下文this調用函數時。 但這一切都在那些鏈接中進行了詳細說明。

一種面向對象的解決方案

對於如何使用OO,我可能會做類似...

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,等等。如果您正在執行單例設置,則可能會過大,但也可以很容易地將其重新排列為真正的單例設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM