0

所以我$scope.property通过将 a 定义为另一个变量的值来复制它var query,并且当我更新它的值时var query会改变$scope.property.

为什么会发生这种情况,我该如何避免这种情况?

我的代码看起来像这样:

var query = $scope.property;
if(condition) {
    console.log($scope.property);
    $.extend(query, anotherObj);
    console.log($scope.property);
}

控制台中的输出如下所示:

> 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"}

我从未在 vanilla javascript 中遇到过这个问题。

4

2 回答 2

2

为什么会发生这种情况

你注意到了query === $scope.property吗?两者都引用完全相同的对象,您可以在两个日志语句之间进行更改。

我怎样才能避免这种情况?

How do you want to avoid this? Do you expect query to be a clone of the object? Then see How do I correctly clone a JavaScript object? or What is the most efficient way to deep clone an object in JavaScript? 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);
于 2013-03-20T19:54:27.853 回答
2
var query = angular.copy($scope.property);
于 2013-06-13T08:35:41.607 回答