Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Created December 17, 2010 17:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unscriptable/745355 to your computer and use it in GitHub Desktop.
Save unscriptable/745355 to your computer and use it in GitHub Desktop.
construct an object given a constructor and an array of parameters
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'
@unscriptable
Copy link
Author

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:

var foo = new Foo.apply([1, 2, 3]);

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.

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