Should I Use Angular.copy() or _.clone()?

2019-01-14 10:20发布

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

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-01-14 10:59

We had some bug reports confirming that using angular.copy does create empty objects on some Windows mobile phones. So if you need to support any version of IE on mobile, don't use angular.copy! Allegedly this bug has been fixed by microsoft, but nevertheless we had to deal with it...

Actually, you can as well use Object.assign()...

Docs: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Further examples: https://googlechrome.github.io/samples/object-assign-es6/

I know it says no IE, but i tried it on my IE11 and it works...

查看更多
不美不萌又怎样
3楼-- · 2019-01-14 11:03

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() on the other hand, is a shallow copy akin to _.clone

Angular.copy vs 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.

Shallow/Deep Copy:

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.

Source

查看更多
登录 后发表回答