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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
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.