I see a lot of code like this:
function Base() {} function Sub() {} Sub.prototype = new Base();
However, if you do:
s = new Sub(); print(s.constructor == Sub);
This is false. This seems confusing to me, since s’s constructor is, indeed, Sub. Is it conventional/better to do this?
function Base() {} function Sub() {} Sub.prototype = new Base(); Sub.prototype.constructor = Sub;
or does it not really matter?
‘constructor’ doesn’t do what it looks like it does. This, in addition to its non-standardness, is a good reason to avoid using it – stick with instanceof and prototype.
Technically: ‘constructor’ is not a property of the ‘s’ instance, it is a property of the ‘Sub’ prototype object showing through. When you create the ‘Sub’ function in Mozilla, you get a newly-minted default Sub.prototype object which has a ‘constructor’ pointing back to the Sub function as a courtesy.
However you then replace that prototype with a new Base(). The original default prototype with the link back to Sub is lost; instead, Sub.prototype is an instance of Base without any overriding ‘constructor’ property. So:
…all the way down to the most basic object whose prototype you didn’t change.
When dealing with JavaScript objects/classes there is no one convention; every library’s metaclass system behaves slightly differently. I haven’t seen one that writes ‘constructor’ to each derived class manually, but it seems as good a solution as any if you really want to have the real constructor available; it will also make the code compatible with browsers/engines that don’t give you ‘constructor’.
I’d consider giving it a different name, though, to avoid confusion with the existing and differently-behaving ‘constructor’ property.