Core JavaScript 1.5 Reference:Global Objects:Object:constructor
From MDC
Contents |
[edit] Summary
Returns a reference to the Object function that created the instance's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name, but it isn't read only (except for primitive Boolean, Number or String values: 1, true, "read-only").
| Property of Object | |
| Implemented in: | JavaScript 1.1, NES2.0 |
| ECMA Version: | ECMA-262 |
[edit] Description
All objects inherit a constructor property from their prototype:
o = new Object // or o = {} in JavaScript 1.2
o.constructor == Object
a = new Array // or a = [] in JavaScript 1.2
a.constructor == Array
n = new Number(3)
n.constructor == Number
Even though you cannot construct most HTML objects, you can do comparisons. For example,
document.constructor == Document document.form3.constructor == Form
[edit] Examples
[edit] Example: Displaying the constructor of an object
The following example creates a prototype, Tree, and an object of that type, theTree. The example then displays the constructor property for the object theTree.
function Tree(name) {
this.name = name;
}
theTree = new Tree("Redwood");
print("theTree.constructor is " + theTree.constructor);
This example displays the following output:
theTree.constructor is function Tree(name) {
this.name = name;
}
[edit] Example: Changing the constructor of an object
The following example shows how to modify constructor value of generic objects. Only true, 1 and "test" variable constructors will not be changed. This example explains that is not always so safe to believe in constructor function.
function Type(){};
var types = [
new Array, [],
new Boolean, true,
new Date,
new Error,
new Function, function(){},
Math,
new Number, 1,
new Object, {},
new RegExp, /(?:)/,
new String, "test"
];
for(var i = 0; i < types.length; i++){
types[i].constructor = Type;
types[i] = [types[i].constructor, types[i] instanceof Type, types[i].toString()];
};
alert(types.join("\n"));