Hello!
I'm trying to implement some kind of class hierarchy in JavaScript. I think I understood the prototype chain, but I still have to sort out the constructor-chaining. Following David Flanagan's Definitive Guide, I wrote
function DerivedClass()
{
BaseClass.apply(this, arguments); // chain constructors
// do some initializations specific to DerivedClass...
}
var foo = new DerivedClass();
where BaseClass()
is a native function of mine written in C++ (I'm
using QtScript). My problem is that then, BaseClass()
is called
as a function, not as a constructor.
I could code BaseClass()
to always behave as a constructor, however it
is called. But I am afraid some day one of my users might forget new
and just write
var bar = BaseClass();
In such a situation, I would like BaseClass()
to do something more
sensible than initializing the global object. For example:
if (!context->isCalledAsConstructor()) fail_gracefully();
But then the constructor chaining fails!
Is there a way I can chain the constructors and have BaseClass()
actually be called as a constructor? Or should I just educate my users
to never forget new
? Right now I'm tempted to replace the test above
by:
if (context->thisObject().strictlyEquals(engine->globalObject()))
fail_gracefully();
but I wonder if there is a cleaner way to handle this.
Thanks!