Skip to content

Instantly share code, notes, and snippets.

@CrabDude
Created July 7, 2011 23:47
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 CrabDude/1070811 to your computer and use it in GitHub Desktop.
Save CrabDude/1070811 to your computer and use it in GitHub Desktop.
Function.prototype.makeCtor: Guarantee Javascript function executes as a constructor.
Function.prototype.makeCtor = function() {
function ctor() {
if (!(this instanceof arguments.callee)) {
return new (arguments.callee.bind.apply(arguments.callee,Array.prototype.concat.apply([null],arguments)));
} else {
that.apply(this,arguments);
}
};
return (Function('var that = this; return '+ctor.toString().replace(ctor.name, this.name))).call(this);
}
var A = (function A(a,b) {
this.a = a;
this.b = b;
}).makeCtor();
A.prototype = {
fizz: 'pop'
};
var B = (function B(a,b) {
this.a = a;
this.b = b;
}).makeCtor();
B.prototype = Object.create(A.prototype);
B.prototype.hello = 'world';
var foo = A(1,2);
foo instanceof A; // true
foo.a === 1; // true
foo.b === 2; // true
var bar = new A(1,2);
bar instanceof A; // true
bar.a === 1; // true
bar.b === 2; // true
var baz = B(3,4);
baz instanceof A; // true
baz instanceof B; // true
baz.hello === 'world'; // true
baz.fizz === 'pop'; // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment