Here is what I would like to do:
function a() { // ... } function b() { // Some magic, return a new object. } var c = b(); c instanceof b // -> true c instanceof a // -> true b instanceof a // -> true
Is it possible? I can make b easily an instance of a by connecting a to my prototype chain, but then I need to make new b() , which I am trying to avoid. I want this to be possible?
Update: I feel this is possible with a reasonable use of b.__proto__ = a.prototype . I will experiment more after work.
Update 2: The following is what seems like the closest you can get, which is enough for me. Thanks to everyone for the interesting answers.
function a() { // ... } function b() { if (!(this instanceof arguments.callee)) { return new arguments.callee(); } } b.__proto__ = a.prototype var c = b(); c instanceof b // -> true c instanceof a // -> false b instanceof a // -> true
Update 3: I found exactly what I wanted on the blog on the Power Constructors blog as soon as I added the essential line b.__proto__ = a.prototype :
var object = (function() { function F() {} return function(o) { F.prototype = o; return new F(); }; })(); function a(proto) { var p = object(proto || a.prototype); return p; } function b(proto) { var g = object(a(proto || b.prototype)); return g; } b.prototype = object(a.prototype); b.__proto__ = a.prototype; var c = b(); c instanceof b
javascript inheritance constructor prototype
pr1001 Dec 11 '09 at 15:59 2009-12-11 15:59
source share