Hiếu Giề
Hiếu Giề

Reputation: 97

Assign value in javascript

I have two objects : $scope.objectA and $scope.objectB. I assign value from $scope.objectA to $scope.objectB like this:

$scope.objectB.value1 = $scope.objectA.value1;

then I make value1 of $scope.objectB to null;

$scope.objectB.value1 = null;

My question is why when I assign $scope.objectB.value1 to null, $scope.objectA.value1 is null too. How can I keep value of $scope.objectA.value1 while changing value of $scope.objectB.value1?

Upvotes: 0

Views: 64

Answers (4)

Muhammad Hamada
Muhammad Hamada

Reputation: 725

The reason is when you assign object to a variable, the assignment will be by reference, so the old and new will be a reference to the original object

enter image description here

So when you edit an object, you're actually editing the original object.

The solution

  1. Angular: use object = angular.copy(myObject1)
  2. jQuery: object = $.extend({}, myObject1);

Upvotes: 1

I think this can happen only if ObjectA and ObjectB refer to the same object on the heap, i.e. it ObjectA and ObjectB are the same objects

$scope['object1'] = {};
$scope['object1']['val'] = {};
$scope['object2'] = {};
$timeout(() => {
  this.$scope['object2']['val'] = this.$scope['object1']['val'];
  $timeout(() => {
   this.$scope['object2']['val'] = null;
      console.log(this.$scope['object1']['val']); // Object {}
    })
});

-

 $scope['object1'] = {};
    $scope['object1']['val'] = {};
    $scope['object2'] = {};
    $timeout(() => {
      this.$scope['object2']['val'] = this.$scope['object1']['val'];
      $timeout(() => {
       this.$scope['object2']['val'] = null;
          console.log(this.$scope['object1']['val']); // null
        })
    });

Upvotes: 1

Egan Wolf
Egan Wolf

Reputation: 3573

Because this is how it works. You make these two variables "bound" together. If you want to keep value of objectA, then use

$scope.objectB.value1 = angular.copy($scope.objectA.value1);

Upvotes: 2

Nighisha John
Nighisha John

Reputation: 409

Make copy of object B and assign it to the object A. Use angular.copy function. It will creates a deep copy of source.

For more information Visit Angular copy doc

$scope.objectA.value1 = angular.copy($scope.objectB.value1);

Upvotes: 3

Related Questions