In JavaScript, every function's prototype object has a non-enumerable property constructor
which points to the function (EcmaScript §13.2). It is not used in any native functionality (e.g. instanceof
checks only the prototype chain), however we are encouraged to adjust it when overwriting the prototype
property of a function for inheritance:
SubClass.prototype = Object.create(SuperClass.prototype, {
constructor: {value:SubClass, writable:true, configurable:true}
});
But, do we (including me) do that only for clarity and neatness? Are there any real-world use cases that rely on the constructor
property?
I can't really see why the constructor
property is what it is in JS. I occasionally find myself using it to get to the prototypes of objects (like the Event object) in IE < 9. However I do think it's there to allow some ppl to mimic classical OO programming constructs:
function Foo()
{
this.name = 'Foo';
}
function Bar()
{
this.name = 'Bar';
}
function Foobar(){};
Foo.prototype = new Foobar;
Foo.prototype.constructor = Foo;
Bar.prototype = new Foobar;
Bar.prototype.constructor = Bar;
var foo = new Foo();
var bar = new Bar();
//so far the set-up
function pseudoOverload(obj)
{
if (!(obj instanceof Foobar))
{
throw new Error 'I only take subclasses of Foobar';
}
if (obj.constructor.name === 'Foo')
{
return new obj.constructor;//reference to constructor is quite handy
}
//do stuff with Bar instance
}
So AFAIK, the "advantages" of the constructor property are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With