A constructor property is a function object that creates and initializes new objects. Each constructor has an associated prototype object that provides inheritance and shared properties.
There are constructor properties belonging to the Global object for all the Built-in (Native) object prototypes. These constructors are available as part of the core language from the global object. They are defined in the ECMA standard at editions 2 and 3. The host implementation may add others for you to use:
Object()
Function()
Array()
String()
Boolean()
Number()
Date()
To create new objects, a new expression is formed with the constructor as its operand. The result is to create a new object by means of the constructor.
For any object the constructor is a property of the prototype. The prototype is a property of the object and the constructor points back at the object. In that sense the prototype and constructor properties each point at the other's parent object.
This needs to hold true for a constructor to be correctly set up:
myObject.prototype.constructor
is the same as:
myObject
They should test true with the === operator since they are supposed to be identical objects.
Both Netscape and MSIE support a constructor property for the Math object. You won't find very many circumstances where you will need to create a new instance of the Math object. Note that the constructor is not a Math object but an Object object, therefore a new Math() statement will produce a new Object object and not a new Math object.
In both cases, attempting to execute a new Math() statement will cause a run-time error. Arguably, this is a bug because objects that should not be instantiated or cloned ought not to support a constructor so that you can sensibly write general-purpose routines that can test for the existence of a constructor property and can then exit gracefully if it is not supported.
The constructor property is supported so inconsistently across the browsers that this kind of test before use approach is almost impossible to deploy.
See also: | Construct, Global object, prototype property |
ECMA 262 edition 2 - section - 4.3.4
ECMA 262 edition 2 - section - 15.1.3
ECMA 262 edition 3 - section - 4.3.4
Prev | Home | Next |
Constructor function | Up | constructor.name |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |