0

I'm using $rootScope.requestObj to store an object of key:values that represent certain filters.

Throughout all my app $rootScope.requestObj is treated a singleton and it's behaviour is as expected.

However, when making a call to an external API, I created a service that received the $rootScope.requestObj as a parameter.

Here's my code:

 function requestHandler(obj /*In my controller I am passing $rootScope.requestObj*/) {

        var internal_object = obj;

        console.log('BEFORE FILTER = ', JSON.stringify($rootScope.requestObj));

        Object.keys(internal_object).forEach(function (key) {
            if (key != 'limit' && key != 'offset' && key != 'cities') {
                internal_object[key] = null;
            } else {
                if (key == 'limit') {
                    internal_object[key] = REQUEST_LIMIT.simplyRETS; //outputs 500 that is simplyRETS limit for a request.
                }
            }
        });
        console.log('AFTER FILTER = ', JSON.stringify($rootScope.requestObj));
       //Rest of the code, I basically serialize the internal_object and send it
       //as params of a $http.get request.

As you can see I am passing $rootScope.requestObj to my internal_object I iterate over the internal object, never modifying the actual $rootScope.requestObj. Still the first console.log outputs this:

Please note 'maxprice' value.

BEFORE FILTER =  {"type":null,"minprice":null,"maxprice":2,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

The second one this =

AFTER FILTER =  {"type":null,"minprice":null,"maxprice":null,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

Somehow in that small iteration where I remove everything from the INTERNAL_OBJECT that is not limit, offset or cities, my $rootScope.requestObj changes and outputs a different value.

Here I'm just testing with maxprice for simplicity. I am using JSON.stringify() to get a stamp of the object's value at the moment.

I believe somehow there's still a link between my internal_object and my $rootScope.requestObj object. However, not sure why and how to avoid it.

Edit

The source of my confusion was that I assumed var internal_object was creating new space in memory. While as explained, it was creating a reference.

Henry Ollarves
  • 509
  • 7
  • 18

1 Answers1

0

Actually, this is the expected behavior, when you use "var internal_object = obj;", you are assigning the memory reference of obj to internal_object, and then you change the values of internal_object, that is the same reference of obj. If you are using angular, just use "var internal_object = angular.copy(obj);", so it will copy the object, instead of using the same memory reference.

Pedro Kehl
  • 166
  • 3
  • 11