-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 }
> 
8
  • 1
    You are incorrect; object b will inherit p1. I can prove it my browser console; maybe your syntax was incorrect when you tried this out? Commented Sep 6, 2014 at 20:33
  • $ node > a = {} {} > a.p1 = 2; 2 > b = Object.create(a); {} > b {} > a { p1: 2 } > Commented Sep 6, 2014 at 20:34
  • Strange, I can reproduce the OP's problem. Commented Sep 6, 2014 at 20:35
  • @wumm - perhaps this is a node bug. Commented Sep 6, 2014 at 20:36
  • 3
    Looks like just a display thing. b.p1 gives 2. Commented Sep 6, 2014 at 20:38

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
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 }

1 Comment

Yes. JSON.stringify does not serialize prototype properties - There is already a relevant SO question : stackoverflow.com/questions/12369543/… The accepted answer has links to ES specs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.