最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Differences between angular.copy() and JSON.parse(JSON.stringify())? - Stack Overflow

programmeradmin6浏览0评论

Can someone explain the differences between angular.copy() and JSON.parse(JSON.stringify())? Are there any? What you will remend to use? Is angular.fromJson(angular.toJson()) the same as JSON.parse(JSON.stringify())?

Just to mention, I've read How do I correctly clone a JavaScript object? for JSON.parse(JSON.stringify()) and angular.copy() reference for angular.copy().

Can someone explain the differences between angular.copy() and JSON.parse(JSON.stringify())? Are there any? What you will remend to use? Is angular.fromJson(angular.toJson()) the same as JSON.parse(JSON.stringify())?

Just to mention, I've read How do I correctly clone a JavaScript object? for JSON.parse(JSON.stringify()) and angular.copy() reference for angular.copy().

Share Improve this question edited May 23, 2017 at 12:34 CommunityBot 11 silver badge asked Apr 21, 2015 at 18:32 Marin TakanovMarin Takanov 1,1384 gold badges20 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

What JSON.parse(JSON.stringify()) won't copy:

  • functions
  • any object that has a special representation, like Date (it will get copied but not as Date)
  • properties with the value undefined

angular.fromJson(angular.toJson()) is basically the same except that angular.toJson() omits properties that are used by Angular internally (those starting with $$).

I can very specifically answer your question by pointing out they treat undefined differently:

> JSON.parse(JSON.stringify(undefined))
SyntaxError: Unexpected token u

And more generally I would prefer angular.copy:

  • angular.copy says exactly what you want; JSON.parse * JSON.stringify is a hack, from a readability standpoint.
  • angular.copy is almost certainly more performant since it is a higher-level specification of what you are trying to do. If the engineers who wrote it wrote something less performant, they would implement it with the JSON version...

That being said, do they treat more esoteric data, such as functions, the same way? I can't answer this off the top of my head but I would research (or wait for another answer) before deciding.

发布评论

评论列表(0)

  1. 暂无评论