We write a lot of JavaScript code to run our automated testing using a tool called TestComplete. In several cases I’ve set up inheritance trees using the following syntax:
function Parent()
{
...
//some inline code here executes on object creation
}
Child.prototype = Parent;
Child.prototype.constructor = Child;
function Child()
{
Parent.call(this);
...
}
The reason I’ve used
Child.prototype = Parent;
instead of
Child.prototype = new Parent();
is because there is code that is executed on the creation of a new object in the parent in some cases. Setting the prototype this way has never been an issue, in that I’ve always been able to call all the functions defined in the Parent after having created a Child.
I suspect, however, I’ve actually broken the prototype chain in doing this and I’ve been saved by the fact that all the methods we define are defined inline (ie. inside the constructor function) and not using the object.prototype.method = … syntax, and so the fact the chain is broken has gone unnoticed.
So I have two questions; have I broken the chain, and what are the side effects of breaking the prototype chain in JavaScript?
When you “break” the prototype chain like this, you cannot access
Parent.prototype.*methods and properties inChildinstances and theinstanceofoperator does not work (new Child() instanceof Parent === false).I understand why you don’t want to use the
newkeyword for the inheritance. There is, however, a little trick to inherit the parent’s prototype whilst not executing the parent’s constructor: