1

I have tried to creates a new object b from object a using Object.create

var a ={}; 
var b = Object.create( a );

a.n = 1;
b.m = 2;

When I iterate two object through for .. in .. its showing correct values . but JSON.stringify not printing correct string .

JSON.stringify( b )

It supposed to print like {"n":1,"m":2} . but it print like {"m":2} only . Any suggestions why?

I have added it in jsfiddle . link of jsfiddle http://jsfiddle.net/V3Nxs/

rab
  • 4,134
  • 1
  • 29
  • 42

3 Answers3

4

This is becasue n is the prototype property of b and JSON.stringify only works for those properties which returns true for hasOwnProperty on the object.

Ankur
  • 33,367
  • 2
  • 46
  • 72
  • 1
    Specifically: `JSON.stringify` only includes *enumerable*, *own* properties, not properties inherited from the prototype, and not non-enumerable properties. – T.J. Crowder May 16 '13 at 11:59
  • @Ankur Your answer helps with my issue. what is solution for print correct `JSON.stringify` ? – rab May 16 '13 at 12:10
1

I updated your fiddle

http://jsfiddle.net/V3Nxs/2/

for( var k in b ){
    if (!b.hasOwnProperty(k)) continue;
    html.push( 'b.'+ k +':' + b[k] );
}
  1. You need to use hasOwnProperty
  2. I changed the index of the second for loop

If you look at what Object.create does, the first argument you pass in is the prototype of the new object. That means that b has everything a has, in the prototype chain. hasOwnProperty fixes this because it only returns true if the property tested is on the object itself, not somewhere up in the prototype chain.

now it behaves as i think you expect.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

b.n not being defined is expected behavior. To get what you want you might want to try this.

var a = {};
var b = {a:a};

a.n = 1;
b.m = 2;

now b.a.n is set to 1 and JSON.stringify includes it in the output.

jabbink
  • 1,271
  • 1
  • 8
  • 20