我有这样的代码:
for (var index = 1; index < args.length; index++) {
var shell = args[index];
listener.of('/' + shell.namespace || 'shotgun')
.on('connection', function (socket) {
socket.on('execute', function (cmdStr, context, options) {
console.log('Received: ' + cmdStr);
var result = shell.execute(cmdStr, context, options);
socket.emit('result', result);
});
});
}
我正在使用socket.io我正在创建多个 namespace 。 socket.io 命名空间运行良好,但在 execute
回调中,对 shell
的引用始终是 for 循环中创建的最后一个对象。我需要循环的每次迭代来保持对该迭代中 shell
的引用。
最佳答案
好吧,最终的答案是使用 let
(ECMAScript 6 或 node --harmony
):
for (let index = 1; index < args.length; index++) {
let shell = args[index];
// ...
}
同时,您可以使用closure ,或一个额外的function
作用域,为每次迭代保留不同的index
和shell
:
function iterator(shell, index) {
listener.of('/' + shell.namespace || 'shotgun')
// ...
}
for (var index = 1; index < args.length; index++) {
iterator(args[index], index);
}
并且,如果 args
是一个 Array
,也可以使用 .forEach()
来完成。 :
args.forEach(function (shell, index) {
listener.of('/' + shell.namespace || 'shotgun')
// ...
});
关于javascript - 如何维护对正确对象的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17730169/