Tim
Tim

Reputation: 31

Javascript function call without defined parameters?

I'm new to javascript and have been following this tutorial series on how sockets work: https://www.youtube.com/watch?v=HZWmrt3Jy10.

He writes:

var io = socket(server);
io.sockets.on('connection', newConnection);

function newConnection(socket){
    console.log('new connection' + socket.id);
}

How does newConnection work in the sockets.on? It needs a socket parameter yet it works, it is a reference to the function as well. I have heard of callbacks vaguely but am still confused. Can someone please explain what is happening.

Upvotes: 0

Views: 45

Answers (2)

slebetman
slebetman

Reputation: 113994

You are passing your function so the socket.on method just like you would be passing a variable. And just like a variable, the code inside socket.on can then use your function including passing you the required parameter.

The socket.on() method would be implemented something like this:

Socket.prototype.on = function (event, callback) {
    // other logic
    callback(socket); // pass socket to your newConnection function
}

So when you call:

io.sockets.on('connection', newConnection);

you are passing your function newConnection as a callback (this can be named anything by the programmer who wrote socket.on) and then it will call your function as:

callback(socket); // callback is second parameter so
                  // in your case it is pointing to
                  // newConnection

so it passes the socket to your function.

Upvotes: 1

6502
6502

Reputation: 114579

Functions in Javascript are "first class" objects and they can be passed around, stored in variables etc... consider this simple example:

function foo(x) {
    console.log("foo(" + x + ") called");
}

function bar(f) {
    f(42);
}

bar(foo);

last line calls the function bar passing it as a parameter the function foo. The function bar then calls the function f that it received passing 42 as argument.

The net result will be the message foo(42) called appearing in console.

In the code you show what happens is that the on function will store away the argument to call it later (providing the socket as parameter) once a connection is established.

Upvotes: 1

Related Questions