First off, this question is not "what does the constructor property do?" - There's plenty of good documentation on exactly what it is and how it works: It's a reference to the function that created the object (which may be inherited from its prototype).
I'm more interested in knowing common use-cases for this property. It seems all good in theory, but when would you actually need a reference to the function that constructed your object? A few ideas would be:
- Perhaps I want to clone it. I could call the constructor again and
get another instance of my object. This of course wouldn't work well since you'd potentially be creating an instance of your object's
prototype, not the object itself; plus a much preferred method would be to create a new object and set that object's prototype instead. - Perhaps you can use it to figure out what the "type" of the object
is. This seems rather odd, since you can use
instanceof
orObject.prototype.toString()
instead. - Can you change or re-assign the constructor? Would there ever be a good reason to do this?
Hopefully some people can chime in with some good Javascript paterns that make use of the constructor reference, or provide an official explanation for why the property exists.