timpone
timpone

Reputation: 19969

is it possible in Javascript to tell an object to stop having reference behavior with another object

Just getting back into doing a lot of Javascript and trying to understand Javascript objects better. I asked previous question earlier but this one is different. Can I disconnect a reference relationship that exists between objects?

For example:

var objA={};
objA.my_name='Joe';
var objB=objA;
objB.my_name="jake"; // objA.my_name="jake"
objB.something="this is something";
objA.last_name="Jackson";
console.log(objA.something);  // "this si something" can add to parent object at runtime
console.log(objB.last_name);  // "Jackson" can add to child object at runtime
// now I'd like to cut off objB from objA such that:
objB.cell_phone='323-213-2323';
console.log(objA.cell_phone); // '323-213-2323' but would like undefined; would like this behavior

thx in advance

Upvotes: 0

Views: 151

Answers (1)

jfriend00
jfriend00

Reputation: 707876

You can't tell an object to stop having reference behavior. That's the way javascript works.

You can copy an object so that you create a totally new object with the same properties as the original, but a completely separate object that won't have reference behavior.

A shallow copy can be made by simply iterating over the properties of an object and assigning each one to a new object.

function shallowCopy(src, dest) {
    for (var prop in src) {
        if (src.hasOwnProperty(prop)) {
            dest[prop] = src[prop];
        }
    }
} 

A shallow copy of an array can be done like this:

var arr = [1,2,3];
var copyArr = [].slice.call(arr, 0);

Deep copies where properties that are objects or arrays themselves are also copied requires more work because you essentially have to check if they are objects or arrays and then recursively copy them and their contents. Shallow copies, as shown here, are much easier and, if you know the contents of your data are often sufficient.


If you want to look at an advanced version of copying (including deep copying), you can see the code for jQuery's .extend() function here. Follow that link and search for fn.extend.

Upvotes: 3

Related Questions