如何创建未连接到原始对象的对象的副本

时间:2022-09-24 18:47:43

I am facing something in my javascript code which I call it a bug but I believe it is technically a feature! So I have a json entity, I create a new one and equalize it to the first one. Now, any change that I perform on the second one, will be affected on the original one as well!

我在我的javascript代码中遇到了一些我称之为bug的东西,但我相信它在技术上是一个功能!所以我有一个json实体,我创建一个新的实体并将其与第一个相等。现在,我在第二个上执行的任何更改也会受到原始更改的影响!

Here is the JSfiddle of simple example I have created: https://jsfiddle.net/Lt7aP/2736/

这是我创建的简单示例的JSfiddle:https://jsfiddle.net/Lt7aP/2736/

given the code:

鉴于代码:

$scope.a = {
    name: "mike",
    age: 10
};

$scope.b = $scope.a;

$scope.b.name = "john";

shouldn't a.name be "mike" and only b.name become "john"? why does it happen to both of them?

不应该a.name是“迈克”,只有b.name成为“约翰”?为什么它们都发生在他们身上?

1 个解决方案

#1


4  

This is definitely not a bug. You have assigned to $scope.b by reference. Since, $scope.b changes, so will $scope.a.

这绝对不是一个bug。您已通过引用分配到$ scope.b.因为,$ scope.b会改变,所以$ scope.a也会改变。

You should use angular.copy for different references.

您应该将angular.copy用于不同的引用。

$scope.b = angular.copy($scope.a);

Fiddle here

在这里小提琴

#1


4  

This is definitely not a bug. You have assigned to $scope.b by reference. Since, $scope.b changes, so will $scope.a.

这绝对不是一个bug。您已通过引用分配到$ scope.b.因为,$ scope.b会改变,所以$ scope.a也会改变。

You should use angular.copy for different references.

您应该将angular.copy用于不同的引用。

$scope.b = angular.copy($scope.a);

Fiddle here

在这里小提琴