What is the `constructor` property really used for? [duplicate]

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:

  • instantiating new objects from instance easily
  • being able to group your objects as being subclasses of a certain class, but still being able to check what particular type of subclass you’re dealing with.
  • As you say: being tidy.

Leave a Comment