Home >Backend Development >PHP Tutorial >About how to use javascript parameters

About how to use javascript parameters

WBOY
WBOYOriginal
2016-08-08 09:06:42953browse

<code>var nickNames = {};

handleMessageBroadcasting = function(socket, nickNames){
    socket.on('message', function(message){
        socket.broadcast.to(message.room).emit('message', {
            text: nickNames[socket.id] + ': ' + message.text
        });
    });
};

handleMessageBroadcasting(socket, nickNames);

</code>

The above handleMessageBroadcasting function uses nickNames internally. Should I pass nickNames as a parameter and then use it? Or should I use it directly as a global variable? Why?

Reply content:

<code>var nickNames = {};

handleMessageBroadcasting = function(socket, nickNames){
    socket.on('message', function(message){
        socket.broadcast.to(message.room).emit('message', {
            text: nickNames[socket.id] + ': ' + message.text
        });
    });
};

handleMessageBroadcasting(socket, nickNames);

</code>

The above handleMessageBroadcasting function uses nickNames internally. Should I pass nickNames as a parameter and then use it? Or should I use it directly as a global variable? Why?

Passing parameters can reduce code coupling

The most taboo thing in programming is global variables. The fewer global variables, the better. Even if the project scale is relatively small, you might as well develop this good habit

It is recommended to pass parameters, global variables may pollute the global environment

Use global variables as much as possible

The people above are right. It is better to pass parameters. I would like to explain my experience in particular, because at that time, I wrote a lot of correct js codes and defined global inversions. When I used parameters in other places, no matter how I set them, it would not work, because it was affected by the global situation.

They all suggest passing parameters, but did you find that the result of passing parameters or globals in your code is the same, there will be and only two nickNames and socket global variables. (Just for current code)

So I feel that it is not a question of the number of global variables, but a question of whether the functional functions need to be well encapsulated.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn