Doubt with syntax

Asked

Viewed 46 times

3

Simple doubt. Usually I see this syntax:

require('../lib/dbconnect')(config);

But I don’t understand why I use those parentheses like that

(....)(....);

Can someone explain to me what this is all about?

2 answers

6

It’s the equivalent of doing it here:

var db = require('../lib/dbconnect');
db(config);

The require function returns the exported value in the dbconnect.js file. This module exported a single function, which you are calling by passing config as parameter.

4


That syntax require('../lib/dbconnect')(config); is used when the module needs to be configured.

I mean, in the module code there’s something like:

var mysql = require('mysql');

module.exports = function (options) {

    var connection = mysql.createConnection({
        host: options.url,
        user: options.user,
        password: options.pass,
        database: options.database
    });
    connection.connect();

    return connection.query; // que é uma função
}

That’s very common when you want to pass one url, secret key, database ip, translation or other to a module.

After configuring it is used as usual:

var db = require('../lib/dbconnect')(config);
db.query('SELECT * FROM tabela', function(err, dados){
    // etc
});

An example in Javascript not necessarily in Node environment would be a speed converter, it occurred to me now! :P

function velocidade(conf){
    return function(KmHora){
        var velocidade = typeof KmHora == 'number' ? KmHora : parseInt(KmHora, 10);
        var ms = velocidade * conf.fator;
        return [ms, conf.unidade].join(' ');
    }
}

So we can set up the unit, and the multiplication factor.

var converter = velocidade({unidade:'m/s', fator: 1/3.6});

And then use the function in n different values:

console.log(converter('300 km/h')); // 83.33333333333334 m/s
console.log(converter(116)); // 32.(2) m/s
console.log(converter(36)); // 10 m/s

jsFiddle: http://jsfiddle.net/b3hrk5u7/

  • Ahh yes... I get it. Is this unique to Node.js? Or this "strange" behavior is reproduced also in libraries that work on the client-side?

  • 1

    @Pedrovinícius can be used in any language that allows returning functions and/or where the scope of the arguments of the first function passes to the internal scope. Whether client- or server-side

  • Could you give an example done in pure Javascript outside of Node.js? I found it interesting...

  • 1

    @Pedrovinícius for example http://jsfiddle.net/b3hrk5u7/, or the Class model has the same idea `var luis = new Animal('human');``

  • Oops! Thank you so much! I understand how this business works hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.