V8 Internals - Handling of Anonymous Functions

前端 未结 1 861
借酒劲吻你
借酒劲吻你 2020-12-10 04:38

For the full story, check out my other question.

Basically, I had asked if it were more efficient to use named functions in the socket handlers for the following cod

1条回答
  •  失恋的感觉
    2020-12-10 05:09

    Yes. I asked a very similar question (related in my case to creating functions from within a constructor function) on the V8 mailing list. I got the reply that the function's code is "...normally reused...", even though there's a separate function object each time (as required by the spec).


    Note, though, that your question has nothing to do with whether the function is named or anonymous. The function in your example could have a name:

    io.sockets.on('connection', function handleConnection(socket) {
        socket.on('action1', function (data) {
            // logic for action1
        });
    
        socket.on('action2', function (data) {
            // logic for action2
        });
    
        socket.on('disconnect', function(){
            // logic for disconnect
        });
    });
    

    That uses a named function expression, which is perfectly valid and handled correctly by V8. (Sadly, it's not handled correctly by IE8 and earlier, which create two completely different functions at totally different times. But as you're using V8, you don't have to worry about that.)

    0 讨论(0)
提交回复
热议问题