Skip to content

Instantly share code, notes, and snippets.

@Avinash-Bhat
Last active December 13, 2015 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Avinash-Bhat/4953291 to your computer and use it in GitHub Desktop.
Save Avinash-Bhat/4953291 to your computer and use it in GitHub Desktop.
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 " + clazz.constructor.name + "(" + 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 + ')');
console.log(xx);
// this is the factory way; cleaner and, better way
var Clazz = window[clazzName];
xx = Object.create(Clazz.prototype)
Clazz.apply(xx, args);
console.log(xx);
@Avinash-Bhat
Copy link
Author

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