Created
July 7, 2011 23:47
-
-
Save CrabDude/1070811 to your computer and use it in GitHub Desktop.
Function.prototype.makeCtor: Guarantee Javascript function executes as a constructor.
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.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