AngularJS : copy vs extend

后端 未结 4 1868
清歌不尽
清歌不尽 2021-01-13 23:27

Explanation :

we come across some situation in which we need to copy one object to another object. In that case, we probably have two solutions: ang

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 00:11

    Primitives are copied by value instead of by reference but first try to understand copy vs extend

    copy

    Iterates each property of an object, if it's a primitive just copy it, if it's an object create a new object and perform a recursive copy

    The implementation may looks as follows, note that obviously there are some additional cases but I'm keeping it simple

    function copy(dest, source) {
      for (var property in source) {
        if (typeof source[property] === 'object') {
          var clone = {}
          copy(clone, source[property])
          dest[property] = clone
        } else {
          // a primitive
          dest[property] = source[property]
        }
      }
    }
    

    extend

    Iterates each property of an object, if it's a primitive just copy it, if it's an object create a reference to the object instead of creating a new object which has the same references as the original object

    function extend(dest, source) {
      for (var property in source) {
        dest[property] = source[property]
      }
    }
    

    Perhaps you're expecting that when you do a shallow copy primitives will also be shallow copied however as you see above they're always cloned, to solve your problem you should instead change properties of a referenced object (achieved with a shallow copy)

    var mySource = {person: {'name' : 'Rohit', 'age' : '24'}}
    var myDest = {}
    angular.extend(myDest,mySource);
    mySource.person.name = "Jindal";
    console.log(mySource); // Object {person: {name: "Jindal", age: "24"}}
    console.log(myDest);  // Object {person: {name: "Jindal", age: "24"}}
    console.log(mySource.obj === myDest.obj); // True
    

提交回复
热议问题