2

I have the following object literal:

var a = {a:1,b:2}

now I want another instance of the same object. If I'm using a constructor, I can do this using the 'new' operator, ie:

b = new a(); 

How to create a new instance of an object using object literals?

user unknown
  • 35,537
  • 11
  • 75
  • 121
Jinu Joseph Daniel
  • 5,864
  • 15
  • 60
  • 90

1 Answers1

3

The simplest way would be with Object.create

var b = Object.create(a);

console.log(b.a); //1
console.log(b.b); //2

DEMO

And of course if you need to support older browsers, you can get the MDN shim for Object.create here

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Using this method, isn't there a risk of creating a memory leak if you aren't careful? If an object were "cloned" like this repeatedly, its prototype chain would grow and all those objects in the prototype chain would never be garbage collected since an active reference to them would remain. It's not a huge problem since most JavaScript scripts are short lived, but I think it would be wise to be aware of this possibility. – Cristian Sanchez Feb 09 '12 at 04:38
  • @CDSanchez - yeah - the new object does seem to share the prototype of the old - [demo](http://jsfiddle.net/eXgx3/1/) - I don't think the prototype would grow though. If you cloned `a` 100 times, you'd have 100 objects with references back to `a`. So yeah, `a` could not be garbage collected, but I don't see that as a huge problem – Adam Rackis Feb 09 '12 at 05:04
  • What I was referring to was if you somehow kept cloning objects that were also cloned. For example, `a = {}; loop 99 times { a = Object.create(a) }` in this case you would have 100 objects with the original at the end of the prototype chain and 99 objects in front. It's not completely inconceivable that someone might do something like this in practice. Anyways, I'll leave it at that since this probably won't affect the OP - I just wanted to point this out. – Cristian Sanchez Feb 09 '12 at 05:33
  • @CDSanchez - oh, yeah - that would be awful. True. – Adam Rackis Feb 09 '12 at 05:52