Skip to content

Instantly share code, notes, and snippets.



Last active Dec 13, 2015
What would you like to do?
Object.create vs (evil) eval for creating an object of different types according to the arguments received.
function createObject (clazz, args) {
var o;
if (Object.create) {
o = Object.create(clazz)
clazz.constructor.apply(xx, args);
} else {
// screwed! nothing other than evil-eval :-(
o = eval("new " + + "(" + args + ")");
function A(x, y) {
this.x = x;
this.y = y
function B(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
// ... in actual case you will be getting the args dynamically, as well as sometimes the prototype too.
var clazzName = 'A'
var args = [1,2];
var xx;
// this is the old (evil) way.
xx = /*evil*/eval('new ' + clazzName + '(' + args + ')');
// this is the factory way; cleaner and, better way
var Clazz = window[clazzName];
xx = Object.create(Clazz.prototype)
Clazz.apply(xx, args);

This comment has been minimized.

Copy link
Owner Author

@Avinash-Bhat Avinash-Bhat commented Feb 14, 2013

Here it is shown how it is possible to create an object with arbitrary arguments without the evil eval.

Disclaimer: This file is for educational purpose only, original may vary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment