0
我正试图使用存储在变量中的键检索对象内部的回调函数集。我正在使用节点v6.3.1。Javascript object not variable value with variable key
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]);
返回[功能],但没有发生。
任何见解?
我们需要看到更多的代码。 server.js如何调用ManageCommands对象?你可以给我们一个jsbin或jsfiddle来重现问题吗? –
在'runCommand'中,请执行:'console.log('command',JSON.stringify(key))',并且报告你得到的结果。 – trincot