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

喜夏-厌秋 提交于 2019-12-17 03:19:50

问题


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?


回答1:


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.



回答2:


Whats my understanding constructor property is used to see whether a particular object is created or constructed by which functional constructor.

This is a great example for the same: http://www.klauskomenda.com/code/javascript-inheritance-by-example/



来源:https://stackoverflow.com/questions/12622137/what-is-the-constructor-property-really-used-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!