Skip to content Skip to sidebar Skip to footer

Will This Copy The Object Or Add A Reference To It?

Let's say I have the following object: var lol = { section: {}, other: {foo: 'bar', foob: 'baz'} }; Now if I do the following: lol.section.other = lol.other; will a refer

Solution 1:

You're creating two references to the same object.

Javascript objects are never implicitly copied.

Solution 2:

Like quite a few other OO languages, JavaScript also passes and assigns the object by reference therefore, you are only creating a new reference to an existing object.

Where JavaScript breaks away from other OO languages is in inheritance and in encapsulation. So be cautious in those areas.

Solution 3:

As SLaks said, javascript assigns objects as a reference (without copying). It's easy to test or see yourself:

var lol = {
    section: {},
    other: {foo: 'bar', foob: 'baz'}
};

lol.section.other = lol.other;

lol.other.foo = 'test';
console.log(lol.section.other.foo);   // will be 'test', not 'bar'

You can see it here: http://jsfiddle.net/jfriend00/r73LH/.

Post a Comment for "Will This Copy The Object Or Add A Reference To It?"