Search code examples
javascriptinheritanceprototypeprototypal-inheritance

JavaScript create and assign a prototype object to another object


I have:

// prototype object
var x = {
    name: "I am x"
};

// object that will get properties of prototype object
var y = {};

// assign the prototype of y from x
y.prototype = Object.create( x );

// check
console.log( y.__proto__ );

Result:

enter image description here

Why? What am I doing wrong?


Solution

  • There is is not such special property as prototype for objects that would act like the one for functions. What you want is just Object.create( x );:

    var x = {
        name: "I am x"
    };
    
    // object that will get properties of prototype object
    var y = Object.create( x );
    
    // check
    console.log( y.__proto__ );
    
    // verify prototype is x
    console.log( Object.getPrototypeOf(y) === x ); // true