Last active
December 16, 2015 17:29
-
-
Save jugglinmike/5470253 to your computer and use it in GitHub Desktop.
Function.prototype.create
This file contains hidden or 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
// Function.prototype.create | |
(function() { | |
var Surrogate = function() {}; | |
Function.prototype.create = function() { | |
if (this.__inst) { | |
return this.__inst; | |
} | |
// Instantiate the instance with support for arbitary constructor arity | |
Surrogate.prototype = this.prototype; | |
Surrogate.prototype.constructor = this; | |
this.__inst = new Surrogate(); | |
this.apply(this.__inst, arguments); | |
return this.__inst; | |
}; | |
}()); | |
// Usage | |
var MyThing = function() {}; | |
var MyOtherThing = function() { | |
this.args = arguments; | |
}; | |
var mt1 = MyThing.create(); | |
var mt2 = MyThing.create(); | |
var mot1 = MyOtherThing.create(1, 2, 3); | |
var mot2 = MyOtherThing.create(); | |
console.log(mt1 instanceof MyThing); | |
console.log(mt1 === mt2); | |
console.log(mot1 instanceof MyOtherThing); | |
console.log(mot1 === mot2); | |
console.log(mot1.args.length === 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment