I’m curious about this design of Javascript, and perhaps any reasons for this architecture or design patterns that can be employed to take advantage of this.
The constructor property of an object is always a reference to the function that created that object, correct?
However, take this code:
function base()
{
this.SayHi = function ()
{
window.alert('Hi');
};
}
function subclass()
{
this.SayBye = function ()
{
window.alert('Bye');
};
}
subclass.prototype = new base();
var s = new subclass();
s.SayHi();
s.SayBye();
window.alert(s.constructor);
The last line will echo the constructor for base, even though we know subclass was called to create the object (otherwise SayBye would not work).
One potential work-around would be to simply do:
subclass.prototype.constructor = subclass;
Perhaps a more concise way of asking my question is why is s.constructor equal to subclass.prototype.constructor and not subclass.constructor, since s is an instanceof subclass. Thanks!
Source.
That’s just how it works. You often do see people explicitly setting the
constructorproperty to something that seems more intuitive to them.