So I'm copying a $scope.property by defining it as the value of another variable var query, and when I update the value of var query it changes the value of $scope.property.
Why does this happen and how can I avoid this?
My code looks something like this:
var query = $scope.property;
if(condition) {
console.log($scope.property);
$.extend(query, anotherObj);
console.log($scope.property);
}
The output in the console looks like this:
> Object {details-type: "order", details-bind_date_formatted: "03/19/2013"}
> Object {details-type: "order", details-bind_date_formatted: "03/19/2013", details-state: "CA"}
I've never encountered this problem in vanilla javascript.
Why does this happen
You noticed that query === $scope.property? The both refer to the exact same object, which you alter between the two log statements.
and how can I avoid this?
How do you want to avoid this? Do you expect query to be a clone of the object? Then see Copying an Object in Javascript or What is the most efficient way to clone a JavaScript object? for that.
I've never encountered this problem in vanilla javascript.
Unlikely, since jQuery is only built of vanilla JS:
var scope = {a:{b:1}};
var a = scope.a;
console.log(scope.a); // or just log(a);
a.c = 0; // or scope.a.c = 0;
console.log(scope.a); // or just log(a);
var query = angular.copy($scope.property);