My app utilizes $rootScope.requestObj to store key-value pairs representing filters.
Throughout the entire application, $rootScope.requestObj is considered a singleton and behaves as expected.
However, when I call an external API, I have a service that takes in $rootScope.requestObj as a parameter.
Below is the code snippet:
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.
Although I pass $rootScope.requestObj to my internal_object, I never directly modify $rootScope.requestObj. Yet, the initial console log shows this:
Note the '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 subsequent log reveals 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}
During the iteration where I clear everything from INTERNAL_OBJECT except limit, offset, or cities, $rootScope.requestObj inexplicably changes and displays a different value.
In this case, I am only focusing on maxprice for simplicity. I'm using JSON.stringify()
to capture the current state of the object's value.
I suspect there may still be some connection between my internal_object and $rootScope.requestObj. However, I'm unsure why this occurs and how to prevent it.
Edit
I was confused because I assumed var internal_object created new memory space. As clarified, it actually created a reference.