Last active
December 13, 2015 18:08
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + ")"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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.