Robert
Robert

Reputation: 10380

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?

Upvotes: 1

Views: 73

Answers (1)

dfsq
dfsq

Reputation: 193261

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

Upvotes: 5

Related Questions