我应该使用 Angular.copy() 还是 _.clone()? [英] Should I Use Angular.copy() or _.clone()?

查看:26
本文介绍了我应该使用 Angular.copy() 还是 _.clone()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个同时依赖 Angular 和 Underscore 的项目.

I'm working on a project that has both Angular and Underscore as a dependency.

当我需要创建一个对象的副本时,根据我当时的心情,我可能会使用 angular.copy()_.clone()

When I need to create a copy of an object, depending on my mood at the time, I might use angular.copy() or _.clone()

我突然想到这些方法中的一种可能比另一种更快/更可靠/更健壮.

It occurs to me that one of these methods is probably more fast/reliable/robust than the other.

假设这两个库都已包含在内,这两个函数中的任何一个是否存在任何已知问题使其比另一个函数更好或更差?

Are there any known issue with either of these functions that make it better or worse to use than the other, assuming both libraries are already included?

推荐答案

关于你的问题: angular.copy 和 _.clone 是不同的.这不是哪个更好的问题,而是关于您需要什么,正如@Kevin B 在评论中所述.

Regarding your question: angular.copy and _.clone are different. It's not a question of which is better, it is about what you need as @Kevin B stated in the comments.

angular.extend() 另一方面,是一个类似于 _.clone 的浅拷贝

angular.extend() on the other hand, is a shallow copy akin to _.clone

Angular.copy 与 Angular.extend

性能方面,我不确定哪个更好,但出于意见考虑,我反对将库包含在任何 Angular 应用程序的全局范围(下划线)中,因为通常这些东西写为 angular 模块.在这种情况下,angular.copy/angular.extend 会胜出.

Performance wise, i'm not sure which is better, but for opinions sake, i'm opposed to including libraries into the global scope (underscore) with any angular app, as usually these things are written as angular modules. angular.copy/angular.extend would win in this case.

浅拷贝/深拷贝:

很简单,如果对象只有原始字段,那么显然你会选择浅拷贝,但如果对象有其他对象的引用,那么根据需求,应该选择浅拷贝或深拷贝.我的意思是,如果引用没有随时修改,那么深度复制就没有意义了.你可以选择浅拷贝.但是如果引用经常被修改,那么你需要去深拷贝.同样没有硬性规定,这完全取决于需求.

Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement.

来源

这篇关于我应该使用 Angular.copy() 还是 _.clone()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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