Startec
Startec

Reputation: 13206

How do javascript libraries ignore certain parameters, or make certain function parameters "optional"?

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?

Upvotes: 2

Views: 567

Answers (4)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

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.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816384

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.

Upvotes: 4

onaclov2000
onaclov2000

Reputation: 5841

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

Upvotes: 0

Gokul Nath KP
Gokul Nath KP

Reputation: 15553

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

Upvotes: 0

Related Questions