angular.copy和赋予对象不同 [英] angular.copy and assign object different

查看:77
本文介绍了angular.copy和赋予对象不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

1.我想知道之间的区别:

var sourceItem = service.getItemByID(id);



$ scope.item = angular.copy(sourceItem);



$ scope.item = sourceItem;



2.我阅读有关服务和工厂的主题。似乎他们只是编码风格不同。这样对吗 ?



谢谢。

Hi all,
1.I want to know what is different between:
var sourceItem = service.getItemByID(id);

$scope.item = angular.copy(sourceItem);
and
$scope.item = sourceItem;

2.I read topics about service and factory . Seems they are only different about coding style. Is it right ?

Thanks.

推荐答案

scope.item = angular.copy(sourceItem);


scope.item = angular.copy(sourceItem);
and


scope.item = sourceItem;



2.我读了有关服务和工厂。似乎他们只是编码风格不同。这样对吗 ?



谢谢。
scope.item = sourceItem;

2.I read topics about service and factory . Seems they are only different about coding style. Is it right ?

Thanks.


当然它们不同: https://docs.angularjs.org/api/ng/function/angular.copy [ ^ ]。



此功能的结果是原始对象的深拷贝。它们是不同的,因为这两个对象将作为独立的对象存在,它们驻留在不同的内存片段中。如果修改源或结果引用引用的对象图中任何对象的任何属性,则另一个对象将保持不变。



如果您只是将一个对象分配给另一个对象,则不会发生这种情况。考虑一下:

Of course they are different: https://docs.angularjs.org/api/ng/function/angular.copy[^].

The result of this function is a deep copy of the original object. They are referentually different, because the two objects will exist as independent objects which reside in different fragments of memory. If you modify any property of any of the objects in the object graph referenced by either source or resulting reference, the other object will remain intact.

This is not what happens if you simply assign one object to another. Consider this:
var a = {a:1, b:2, c:3}
var b = a
b.a = 13
// now a.a == 13
// a and b are two different variables
// referencing the same object



与它比较


Compare it with

var a = {a:1, b:2, c:3}
var b = {} // not a, different reference
b.a = a.a; b.b = a.b; b.c = a.c;
b.a = 13
// still a.a == 1
// a and b are independent objects

理解参考和价值对象是一般编程的核心。你需要完全理解这些事情,做几乎任何类型的编程。



我用了一个例子,其中深拷贝与浅拷贝没什么不同。当某些对象的元素也是一些非基本对象时,需要进行深层复制,依此类推。浅拷贝保持引用相同的属性,深拷贝以递归方式克隆所有属性的所有对象。



-SA

Understanding of reference and value objects lie in the very heart of general programming. You need to understand such things perfectly, to do nearly any kind of programming.

I used an example where deep copy is no different from shallow copy. Deep copy is needed when element of some objects are also some non-primitive objects, and so on. Shallow copy keeps the referentially identical properties, and deep copy clones all objects of all properties recursively.

—SA


这篇关于angular.copy和赋予对象不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆