Javascript对象没有使用变量键返回值

时间:2016-07-22 23:27:10

标签: javascript node.js

我试图使用存储在变量中的键来检索对象内部的回调函数集。我使用的是节点v6.3.1。

function ManageCommands() {
    var scope = this;
    scope.commands = {};

    return {
        addCommand: function (command, callback) {
            scope.commands[command] = callback;
        },
        compileCommands: function () {
            return Object.keys(scope.commands);
        },
        runCommand: function (key) {
            console.log('command', key);
            console.log('commands', scope.commands);
            console.log(scope.commands[key]);
        }
    };
}

但是,当尝试访问runCommand中的回调函数时,它返回undefined。:

$ node server.js
command test me
commands { hello: [Function], 'test me': [Function] }
undefined

$ node server.js
command hello
commands { hello: [Function], 'test me': [Function] }
undefined

我觉得我错过了一些非常简单的东西,命令以字符串形式返回。

我希望console.log(scope.commands[key]);返回[功能],但这不会发生。

任何见解?

1 个答案:

答案 0 :(得分:0)

Console.log不会为返回和新行打印特殊字符。

我将字符串推入了一个我输出的数组:

[ 'hello\r' ]

我剥离了返回,我的功能按预期工作。