Last active
December 13, 2015 16:39
-
-
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)
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
/** | |
* 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