Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  148] [ 1]  / answers: 1 / hits: 16209  / 10 Years ago, mon, july 14, 2014, 12:00:00

While I was working on a project, I came across this snippet of code:



var params = JSON.parse(JSON.stringify(defaultParams));


Does this code actually do anything?


More From » json

 Answers
17

It's a way of cloning an object, so that you get a complete copy that is unique but has the same properties as the cloned object.



var defaultParams = { a : 'b' };
var params = JSON.parse(JSON.stringify(defaultParams));

console.log( params.a ); // b
console.log( defaultParams.a ); // b
console.log( params === defaultParams ); // false


The above outputs false because even though both objects have the a property, with the value b, there are different objects that are independent of each other (they don't refer to the same reference).



The JSON method will only work with basic properties - no functions or methods.


[#70212] Friday, July 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;