Skip to content

Instantly share code, notes, and snippets.

@jugglinmike
Last active December 16, 2015 17:29
Show Gist options
  • Save jugglinmike/5470253 to your computer and use it in GitHub Desktop.
Save jugglinmike/5470253 to your computer and use it in GitHub Desktop.
Function.prototype.create
// 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