Object.create and Prototypes

238 Views Asked by At

When I use object.create to create a new object like so,

o = {x:1,y:2};
p = Object.create(o);

I'm under the impression that o becomes the prototype of p and inherits all its methods.

Then why, when I try

print(p.prototype);

the output is undefined? o is well-defined!!

Thank You

2

There are 2 best solutions below

0
On BEST ANSWER

Only functions have a prototype property [ES5].

p references o through the internal [[Prototype]] property, which was accessible in some browsers with __proto__ [MDN], but is now deprecated.

You can get a reference to the prototype of an object with Object.getPrototypeOf [MDN]:

Object.getPrototypeOf(p) === o // true
0
On

Try this, o becomes the prototype of p means o is the prototype of p's constructor.

console.log(p.constructor.prototype);

var o = {x:1,y:2};
var p = Object.create(o);

You could image above as below:

var o = {x:1,y:2};
function constructor_of_p(){};
constructor_of_p.prototype = o;
var p = new constructor_of_p();