Why and when to use angular.copy? (Deep Copy)

前端 未结 7 732
無奈伤痛
無奈伤痛 2020-12-04 07:39

I\'ve been saving all the data received from services direct to local variable, controller, or scope. What I suppose would be considered a shallow copy, is that correct?

7条回答
  •  一整个雨季
    2020-12-04 07:56

    Javascript passes variables by reference, this means that:

    var i = [];
    var j = i;
    i.push( 1 );
    

    Now because of by reference part i is [1], and j is [1] as well, even though only i was changed. This is because when we say j = i javascript doesn't copy the i variable and assign it to j but references i variable through j.

    Angular copy lets us lose this reference, which means:

    var i = [];
    var j = angular.copy( i );
    i.push( 1 );
    

    Now i here equals to [1], while j still equals to [].

    There are situations when such kind of copy functionality is very handy.

提交回复
热议问题