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?
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?
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/
Browser other questions tagged javascript node.js pattern-design syntax
You are not signed in. Login or sign up in order to post.
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?
– Pedro Vinícius
@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
– Sergio
Could you give an example done in pure Javascript outside of Node.js? I found it interesting...
– Pedro Vinícius
@Pedrovinícius for example http://jsfiddle.net/b3hrk5u7/, or the Class model has the same idea `var luis = new Animal('human');``
– Sergio
Oops! Thank you so much! I understand how this business works hehe
– Pedro Vinícius