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

前端 未结 1 1987
走了就别回头了
走了就别回头了 2021-01-26 08:07

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 disconnec

相关标签:
1条回答
  • 2021-01-26 08:41

    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.

    0 讨论(0)
提交回复
热议问题