2

I will use Node.js as an example but I see this in many docs:

(From the net module documentation):

net.createConnection(port, [host], [connectListener])

Creates a TCP connection to port on host. If host is omitted, 'localhost' will be assumed. The connectListener parameter will be added as an listener for the 'connect' event.

This is followed with example code such as the following:

a = net.createConnection(8080, function(c){
    console.log('do something');
});

My question is that the createConnection function takes from 1 - 3 parameters. Above, I passed in two. How is it that Node is able to know the function argument I passed in is meant as the connectListener argument and not the host argument?

Startec
  • 12,496
  • 23
  • 93
  • 160

4 Answers4

4

If the parameters have different types, you can simply test for them. Here port is probably a number, host a string and connectionListener is a function.

For example:

function createConnection(port, host, connectionListener) {
    if (typeof host === 'function') {
        conectionListener = host;
        host = null;
    }
    if (!host) {
        host = 'localhost';
    }
    // ...
}

Of course this doesn't work if the parameters are of the same type. There is no a general solution for that case.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

I don't specifically know the implementation of createConnection, but one possible way to do this would be to count the arguments passed to the function as well as checking their type, something like:

function createConnection(port, host, connectListener) {
    var f = connectListener;
    if(arguments.length === 2 && typeof host === "function") {
        f = host;
        host = "localhost";
    }
    console.log("Host: " + host);
    console.log("Port: " + port);
    f();
}

createConnection(8080, function() { 
    console.log("Connecting listener...");
});

Here is a fiddle.

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

Maybe it is internally calling net.createConnection(options, [connectionListener]), so that the parameters are mapped properly.

Reference:

http://nodejs.org/api/net.html#net_net_createconnection_options_connectionlistener

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
0

The type can be inspected, thus checking parameter 2 is a function allows such behavior Handling optional parameters in javascript

Community
  • 1
  • 1
onaclov2000
  • 5,741
  • 9
  • 40
  • 54