Reputation: 94
I want to create an object dynamically in node. To do that i used a code like this. Is this use of eval in a node server a bad idea?
var a1 = require(./a1.js),
a2 = require(./a2.js),
...
aN = require(./aN.js);
function createObj(pObjName, pObjValue){
var tmp = new eval(pObjName)(pObjValue);
//where pObjName is a1 or a1 or .... or aN
}
Upvotes: 0
Views: 92
Reputation: 51866
If you want to save yourself the time of declaring all of those dependencies, you could even write a function without using eval
that handles the case even more efficiently:
function createObj(pObjName, pObjValue) {
var tmp = new (require('./' + pObjName))(pObjValue);
// ...
}
Please note that this is only safe if createObj()
is guaranteed to be invoked with a pObjName
that is what you expect, otherwise you'll need to validate it first, possibly something like this:
function createObj(pObjName, pObjValue) {
if (!/^a\d$/.test(pObjName)) {
throw new TypeError('invalid name')
}
var tmp = new (require('./' + pObjName))(pObjValue);
// ...
}
Upvotes: 0
Reputation: 203286
From what you're showing, there's no need to use eval
:
const Classes = {
a1 : require('./a1'),
a2 : require('./a2'),
...
};
function createObj(pObjName, pObjValue){
var tmp = new Classes[pObjName](pObjValue);
...
}
Upvotes: 3
Reputation: 1046
Seems like you want to create objects with a set of properties?
You might want to look at the Object.create()-method
Upvotes: 1