JavaScript 回调的效率 [英] Efficiency with JavaScript Callbacks
问题描述
我只是想确认一下我的怀疑.
I just wanted to confirm a suspicion of mine.
我偶然发现了一篇文章,它推荐以下列方式使用 Socket.io:
I stumbled across an article which recommended using Socket.io in the following fashion:
var app = require('express').createServer()
var io = require('socket.io').listen(app);
app.listen(8080);
// Some unrelated stuff
io.sockets.on('connection', function (socket) {
socket.on('action1', function (data) {
// logic for action1
});
socket.on('action2', function (data) {
// logic for action2
});
socket.on('disconnect', function(){
// logic for disconnect
});
});
我觉得以下内容会更好地利用资源:
I feel like the following would be a better use of resources:
var app = require('express').createServer()
var io = require('socket.io').listen(app);
app.listen(8080);
// Some unrelated stuff
io.sockets.on('connection', function (socket) {
socket.on('action1', action1);
socket.on('action2', action2);
socket.on('disconnect', disconnect);
});
function action1(data) {
// logic for action1
}
function action2(data) {
// logic for action2
}
function disconnect() {
// logic for disconnect
}
我的感觉是,虽然处理connection
事件的匿名函数只在内存中创建了一次,但是处理action1
、action2
和 disconnect
在内存中为每个套接字连接创建.第二种方法的问题是 socket
不再在范围内.
My feeling is that although the anonymous function that handles the connection
event is only created in memory once, the anonymous functions that handle action1
, action2
, and disconnect
are created in memory for every socket connection. The issue with the second approach is that socket
is no longer in scope.
那么首先,我对函数创建的怀疑是真的吗?其次,如果是这样,有没有办法让 socket
在命名函数的范围内?
So firstly, is my suspicion about the creation of functions true? And secondly, if so is there a way to get socket
in scope for the named functions?
推荐答案
使用闭包有助于保持范围干净:
Using a closure helps to keep the scope clean:
io.sockets.on('connection', function () {
function action1(data) {
// logic for action1
}
function action2(data) {
// logic for action2
}
function disconnect() {
// logic for disconnect
}
return function (socket) {
socket.on('action1', action1);
socket.on('action2', action2);
socket.on('disconnect', disconnect);
}
}()); // <- note the immediate function call
回答您的问题:
那么首先,我对函数创建的怀疑是真的吗?
So firstly, is my suspicion about the creation of functions true?
是的.上面的闭包方法防止了这种情况,回调函数只创建一次.另外:都看到正确的父作用域.
Yes. The closure approach above prevents this, the callback functions are created only once. Plus: all see the correct parent scopes.
其次,如果是这样,有没有办法让 socket
在命名函数的范围内?
And secondly, if so is there a way to get
socket
in scope for the named functions?
socket
将在回调中作为 this
使用.
The socket
will be available as this
in the callbacks.
这篇关于JavaScript 回调的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!