mozilla
Your Search Results

    constructor

    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. The value is only read-only for primitive values such as 1true and "test".

    Description

    All objects inherit a constructor property from their prototype:

    var o = {};
    o.constructor === Object; // true
    
    var a = [];
    a.constructor === Array; // true
    
    var n = new Number(3);
    n.constructor === Number; // true

    Examples

    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;
    }
    
    var theTree = new Tree( "Redwood" );
    console.log( "theTree.constructor is " + theTree.constructor );

    This example displays the following output:

    theTree.constructor is function Tree (name) {
        this.name = name;
    }

    Example: Changing the constructor of an object

    The following example shows how to modify constructor value of generic objects. Only true, 1 and "test" will not be affected as they have read-only native constructors. This example shows that it is not always safe to rely on the constructor property of an object.

    function Type () {}
    
    var types = [
        new Array(),
        [],
        new Boolean(),
        true,             // remains unchanged
        new Date(),
        new Error(),
        new Function(),
        function () {},
        Math,	
        new Number(),
        1,                // remains unchanged
        new Object(),
        {},
        new RegExp(),
        /(?:)/,
        new String(),
        "test"            // remains unchanged
    ];
    
    for( var i = 0; i < types.length; i++ ) {
        types[i].constructor = Type;
        types[i] = [ types[i].constructor, types[i] instanceof Type, types[i].toString() ];
    }
    
    console.log( types.join( "\n" ) );

    Specifications

    Specification Status Comment
    ECMAScript 1st Edition. Implemented in JavaScript 1.1 Standard Initial definition.
    ECMAScript Language Specification 5.1th Edition (ECMA-262) Standard  
    ECMAScript Language Specification 6th Edition (ECMA-262) Draft  

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support (Yes) (Yes) (Yes) (Yes) (Yes)
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

     

    Document Tags and Contributors

    Contributors to this page: Sevenspade
    Last updated by: Sevenspade,