I have a function to help me create ad hoc objects and save me time typing.
Additional EDIT: to clarify this function will only ever sit inside an anon function.
(function(){ // clarification of the functions location
var objectPump = function (props, defaults){
var str;
if(typeof defaults === "string"){
defaults = defaults.split(",");
}else
if(typeof defaults === "undefined" || !defaults.isArray){
defaults =[];
}
if(props !== undefined){
if(typeof props === "string"){
props = props.split(",");
}
}else{
throw new TypeError("No properties defined for objectPump.");
}
// create function body
str = "var obj={};";
props.each( function(p,i) {
str += "obj." + p + "=";
if (typeof defaults[i] === "string") {
str += p + "===undefined?" + '"' + defaults[i] + '":';
} else
if (typeof defaults[i] === "number") {
str += p + "===undefined?" + defaults[i] + ":";
}
str += p + ";";
});
str += "return obj;";
str = "return new Function('" + props.join("','") + "','" + str + "')";
// Uses new Function to create the new function
return (new Function(str))(); // Is this dangerous???
}
})(); // wrapped in an anon function
Which lets me create objects without having to name all the properties and code in defaults.
Edit: Use of the above function.
var car = objectPump("colour,year,type", // objects property names
"white,2015,All Wheel Drive"); // object defaults
// or as arrays
var car = objectPump(["colour","year","type"], // objects property names
["white",2015,"All Wheel Drive"]); // object defaults
var cars = [
car("red",2011), // missing property defaults to All Wheel Drive
car("blue",2015,"bike"),
];
var aCar = car("blue",2015,"bike");
// same as
var aCar = {
colour:"blue",
year:2015,
type:"bike"
}; // but saves me having to type out the property names for each new object
To me it looks very similar to using eval and a place a third party harker could get some malicious code in. So far it has been very handy and I am tempted to use new Function
for other tasks.
Should I use new Function()
to generate code or is it considered bad and/or dangerous for public code.