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:
instanceof
or
Object.prototype.toString()
instead.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.
The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. Note: This is a property of JavaScript objects.
Description. A constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object.
In JavaScript, the Constructor method is invoked when you create an instance of a class. It is also used to initialize objects within a class. However, JavaScript will automatically create and execute an empty constructor if you have not defined any constructor method for a class.
So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
One case where the constructor property is handy (or would be if it was reliable) is where a function needs to know the type of argument it has been passed, e.g.
function foo(arg) {
if ( /* if arg is an array */ ) {
// deal with array
} else if ( /* if arg is an object */ ) {
// deal with object
}
}
If the above function is passed an array or object, then typeof
will return object in both cases. The constructor property can be used:
if ( arg.constructor == Array )
But that fails if the array is created in a different frame to where the test is taking place (i.e. it's Array constructor is a different object to the Array function in the scope of the test).
So if you rule out frames (or other cases where scope is an issue), then the constructor property is fine to use for this.
But that does not fix the general issue of the constructor property being writable (and therefore can be set to anything) and cases where the prototype chain is more than trivial.
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