Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 593
Bergi Avatar asked Nov 04 '22 15:11

Bergi


1 Answers

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.
like image 66
Elias Van Ootegem Avatar answered Nov 15 '22 01:11

Elias Van Ootegem