-2

When an object is created using Object.create(someObject) method the properties of the original method is not derived by the created method. How to make it derive the existing properties.?

> a = {}

> a.p1 = '8'; // add a property to object

> b = Object.create(a);

> b // b does not inherit the property p1.
{}

To reproduce the bug use the node console as shown below:

$ node
> a = {}
{}
> a.p1 = 2;
2
> b = Object.create(a);
{}
> b
{}
> a
{ p1: 2 }
> 
Talespin_Kit
  • 20,830
  • 29
  • 89
  • 135

2 Answers2

3

Prototype properties will not be a part of string representation printed to console.

You can verify that b.p1 can indeed be called and the corresponding value is 2

You can also try printing b.__proto__ which gives { p1: 2 }

lorefnon
  • 12,875
  • 6
  • 61
  • 93
  • 2
    Yes. JSON.stringify does not serialize prototype properties - There is already a relevant SO question : http://stackoverflow.com/questions/12369543/why-is-json-stringify-not-serializing-prototype-values The accepted answer has links to ES specs. – lorefnon Sep 06 '14 at 20:58
3

There's no bug all is working correctly. From MDN:

The Object.create() method creates a new object with the specified prototype object and properties.

The object is created with a prototype but prototypes are never shown in node (and in any browser console I know). You can see the prototype by using b.__proto__

enter image description here

idmean
  • 14,540
  • 9
  • 54
  • 83
  • Just curious. About like 5 minutes ago you had thought reproducing the problem was strange which means you were not aware of the answer. How did you manage to find the answer so fast. – Talespin_Kit Sep 06 '14 at 20:48
  • @Talespin_Kit After trying it out in the node console I checked the MDN documentation to make sure I remembered correctly what Object.create does. And there I just realized that it creates an object from a prototype. So I tried displaying the prototype and indeed it worked. – idmean Sep 06 '14 at 20:50