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?

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.