Created
December 1, 2012 15:21
-
-
Save cjwainwright/4182867 to your computer and use it in GitHub Desktop.
A function to create a new object using a constructor function when you only have an array of arguments, analogous to how you would use "apply" to call a function, but for "new".
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
// A function to create a new object using a constructor function when you only | |
// have an array of arguments, analogous to how you would use "apply" to call a | |
// function, but for "new". | |
function make(C, args) { | |
function T(){ | |
C.apply(this, args); | |
} | |
T.prototype = C.prototype; | |
return new T(); | |
} | |
// Example usage: | |
function F(a, b) { | |
this.a = a; | |
this.b = b; | |
} | |
F.prototype.foo = function(){console.log('foo');}; | |
var o = make(F,[1,2]); | |
// Check we created the same object as we would have with var o = new F(1, 2); | |
console.log(o.a); // 1 | |
console.log(o.b); // 2 | |
o.foo(); // 'foo' | |
console.log(o.constructor == F); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note an ES5 version, such as
works even on functions that have different call and construct behaviour, such as
String
Date
etc. - see https://twitter.com/littlecalculist/status/330757690743746561