[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/new-object-same-constructor [Back]  [Original]

Create an object with the same constructor
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Create an object with the same constructor

    importance: 5

    Imagine, we have an arbitrary object obj, created by a constructor function we dont know which one, but wed like to create a new object using it.

    Can we do it like that?

    let obj2 = new obj.constructor();

    Give an example of a constructor function for obj which lets such code work right. And an example that makes it work wrong.

    solution

    We can use such approach if we are sure that "constructor" property has the correct value.

    For instance, if we dont touch the default "prototype", then this code works for sure:

    function User(name) {
      this.name = name;
    }
    
    let user = new User('John');
    let user2 = new user.constructor('Pete');
    
    alert( user2.name ); // Pete (worked!)

    It worked, because User.prototype.constructor == User.

    But if someone, so to speak, overwrites User.prototype and forgets to recreate constructor to reference User, then it would fail.

    For instance:

    function User(name) {
      this.name = name;
    }
    User.prototype = {}; // (*)
    
    let user = new User('John');
    let user2 = new user.constructor('Pete');
    
    alert( user2.name ); // undefined

    Why user2.name is undefined?

    Heres how new user.constructor('Pete') works:

    1. First, it looks for constructor in user. Nothing.
    2. Then it follows the prototype chain. The prototype of user is User.prototype, and it also has no constructor (because we forgot to set it right!).
    3. Going further up the chain, User.prototype is a plain object, its prototype is the built-in Object.prototype.
    4. Finally, for the built-in Object.prototype, theres a built-in Object.prototype.constructor == Object. So it is used.

    Finally, at the end, we have let user2 = new Object('Pete').

    Probably, thats not what we want. Wed like to create new User, not new Object. Thats the outcome of the missing constructor.

    (Just in case youre curious, the new Object(...) call converts its argument to an object. Thats a theoretical thing, in practice no one calls new Object with a value, and generally we dont use new Object to make objects at all).


    Web Proxy Viewer  |  New URL  |  Original Page