Created
December 17, 2010 17:47
-
-
Save unscriptable/745355 to your computer and use it in GitHub Desktop.
construct an object given a constructor and an array of parameters
This file contains 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 (ctor, args) { | |
function F () { | |
ctor.apply(this, args); | |
} | |
F.prototype = ctor.prototype; | |
F.prototype.constructor = ctor; // IE might need this | |
return new F(); | |
} | |
// quick test: | |
function Foo(a,b,c) { | |
this.a = a; this.b = b; this.c = c; | |
} | |
createObject(Foo, [1,2,3]) instanceof Foo; // true | |
createObject(Foo, [1,2,3]).a // 1 | |
/* another way to do it: create a generic constructor that takes an array of parameters */ | |
function makeCtor (ctor) { | |
function F (args) { | |
ctor.apply(this, args); | |
} | |
F.prototype = ctor.prototype; | |
F.prototype.constructor = ctor; // IE might need this | |
return F; | |
} | |
var ctor = makeCtor(Foo); | |
new ctor([1, 2, 3]) instanceof Foo; // true | |
new ctor(['a', 'b', 'c']).a // 'a' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something like this could be needed in a generic routine that constructs objects from meta data (json-schema for instance). You may expect that this would work:
but it doesn't.
The really cool part (imho) is that obj instanceof F is true, but no code could test for that since F is scoped locally to the createObject and makeCtor functions.