Search code examples
javascriptprototypal-inheritanceobject-create

Inheritance and Object.Create in Javascript


look at this code :

        var Test = {
        options: {
            name: 'foo'
        },
        name: 'foo',
        init: function (name) {
            this.name = name;
            this.options.name = name;
        }
    };

    var dict = {};

    for (var i = 0; i < 3; i++) {
        var obj = Object.create(Test);
        obj.init(i);
        dict[i] = obj;
    }

i don't understand why all the properties in dict[X].options.name in the object dict has the value same value(2) and the propertiesin dict[X].name has different value ?


Solution

  • I think you are a bit confused here.

    options: {
        name: 'foo'
    },
    name: 'foo'
    

    as you defined them, and then used in your Object.create() statement, belong to the prototype and as such are the same for all objects with the same prototype.

    The reason you see name attribute changed is because you created it on each instance (essentially overriding that defined in the prototype) by calling:

    this.name = name;
    

    Something that doesn't happen for the object property because you never assigned it directly. Instead it takes the last assigned value (which would be 2 in your example).

    Had you written:

    this.options = {};
    this.options.name = name;
    

    in your init function - options.name would be overridden on each instance and be just like you wanted it.