Skip to content

Instantly share code, notes, and snippets.

@jayphelps
Last active December 13, 2015 16:39
Show Gist options
  • Save jayphelps/4942016 to your computer and use it in GitHub Desktop.
Save jayphelps/4942016 to your computer and use it in GitHub Desktop.
newApply() - A simple way to combine `foo.apply(context, args)` with `new Foo()` at the same time. (apply an array of arguments to the constructor of the new object instance)
/**
* newApply
* By Jay Phelps
* WTFPL Licensed
*
* Example:
*
* function Foo(first, second) {
* alert(first + ' ' + second);
* }
*
* var foo = newApply(Foo, ['hello', 'world']);
*/
var newApply = (function () {
// Locally overriding the built-in Object temporarily allows us (in most
// browsers) to maintain the original constructor's name when it is printed
// in the console. Otherwise, what ever we name this, that name will be used
// instead.
var Object = function () {};
return function(ctor, args) {
// Reference prototype
Object.prototype = ctor.prototype;
Object.prototype.constructor = ctor;
// Original constructor not provided to prevent double
// firing on the real object
var instance = new Object();
ctor.apply(instance, args);
return instance;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment