Skip to content

Instantly share code, notes, and snippets.

@cjwainwright
Created December 1, 2012 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjwainwright/4182867 to your computer and use it in GitHub Desktop.
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".
// 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
@cjwainwright
Copy link
Author

Note an ES5 version, such as

function make(C, args) {
  return new (Function.prototype.bind.apply(C, [null].concat(args)));
};

works even on functions that have different call and construct behaviour, such as String Date etc. - see https://twitter.com/littlecalculist/status/330757690743746561

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