1

I began writing code assuming that:

person1 = person 

will give me a new instance, it doesn't. person1 is actually a reference/pointer to person.

person = {age : 2}

person1 = person;

person.age = 3;

alert(person1.age); //gives us 3.

How do I make a new instance without changing much code around? I have like 300 lines of code inside the object, functions(methods?) and everything. Wouldn't want to rewrite as a constructor.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • ... 300 lines of code? Why not just do it right? You have almost nothing. – Dave Newton Aug 06 '14 at 12:56
  • can we see a bit more of the real person object? The answer varies a lot between cloning a hash, a function, a model, etc. – ffflabs Aug 06 '14 at 12:57
  • Who downvoted the question? It has spawn a ton of answers, and each one has comments. This is the kind of questions we want to see more often. – ffflabs Aug 06 '14 at 13:04
  • @Dave, I know it's not much, and I don't know the proper way to do it in the first place. Well, now assuming that it's to create a constructor, since that's what I think you're suggesting. I'll do it the proper way if there's no quick and dirty path. – user3279266 Aug 06 '14 at 13:12

4 Answers4

2

You need to clone an object if you want a new instance.

One (shallow) way of cloning is to use JSON.stringify and JSON.parse. Note that this won't copy methods correctly:

var person1 = JSON.parse(JSON.stringify(person))

More accurately, you can iterate through your person object and apply the key-values to a new object instance ({}) if you want to copy methods (etc.). An "elegant" way to do this is demonstrated in this answer:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

That being said, there are tons of different ways to clone. Check out this SO post for comparisons.

Community
  • 1
  • 1
Casey Falk
  • 2,617
  • 1
  • 18
  • 29
  • @Downvoter? Care to explain why? – Casey Falk Aug 06 '14 at 12:47
  • Does this work for functions and circular structures? – ma08 Aug 06 '14 at 12:51
  • The stringify-parse strategy will ***not*** (it's shallow). The other methods in the SO post and the iteration method ***will***. See the updated answer. : ) – Casey Falk Aug 06 '14 at 12:52
  • I have like 300 lines of code inside the object, **functions(methods?)** and everything. You should have chosen a better option to demonstrate rather than relying on the link, or you should have flagged it as a duplicate? – ma08 Aug 06 '14 at 12:54
  • *"Alternatively, you can iterate through your person object and apply the key-values to a new object instance ({}) if you want to copy methods (etc.)."* -- Does this not suffice as a "better option"? And I didn't see this as a duplicate. OP asked how to create a new instance of an object, ***not*** for the most efficient way to clone something. Those are completely different questions. – Casey Falk Aug 06 '14 at 12:56
  • And yup -- "methods" are function members of an object. :) – Casey Falk Aug 06 '14 at 12:59
  • 1
    Sorry, I got it now and your answer makes more sense now. :) – ma08 Aug 06 '14 at 16:00
0

If you use underscore, try this:

person1 = _.clone(person);

Kris Ku
  • 1,507
  • 1
  • 16
  • 32
0

Shallow copies, such as underscore's, or JSON parse+strinfigy won't copy functions (if you have any).

Depending on the structure of your current person object, it might be enough to do

person1= new person();

JS doesn't have a real "class" object type. Functions can be treated as classes in most cases.

Keep in mind that any person's properties that are, in turn, a reference to a global object, will be common among all instances of person. That's not necesarily a bad thing. I've seen class properties used as a datastore to make instances talk among themselves.

EDIT: I remembered about a post I read long ago about an "elegant way to deep clone objects". It helped me a lot back then. It's meant to clone objects and properties of variable depth, but again, it won't copy methods.

Community
  • 1
  • 1
ffflabs
  • 17,166
  • 5
  • 51
  • 77
  • 1
    Your code will result in [object Object] is not a function, it is object. exception See the OP code person = {age : 2}; – Zlatin Zlatev Aug 06 '14 at 12:51
  • That's right, the current example given in the question is a shallow object and you can't instance it. That's why I said "depending on the structure of your current object". Models are objects too. Have an upvote for reminding me not to make assumptions. – ffflabs Aug 06 '14 at 12:55
0

See Object.assign (ES6 feature) http://www.2ality.com/2014/01/object-assign.html

https://github.com/sindresorhus/object-assign

Zlatin Zlatev
  • 3,034
  • 1
  • 24
  • 32