Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  23] [ 1]  / answers: 1 / hits: 71629  / 10 Years ago, mon, july 21, 2014, 12:00:00

I create an object with multiple properties -



var objOpts = {
option1: 'Option1',
option2: 'Option2',
option2: 'Option3'
};


I then add some more properties later on -



objOpts.option4 = 'Option4'
objOpts.option5 = 'Option5'


I'm then done with the two latter created properties ('Option4' & 'Option5') and I want to clear/delete both.



Currently I'd do it like so -



delete objOpts.option4
delete objOpts.option5


Is there another way to go about doing this? Imagine I'd added 5 more properties and needed to clear/delete them all that'd be five lines of almost identical 'delete' code


More From » oop

 Answers
46

I'm sure you are trying to add custom properties to an object.



A simpler way I would suggest is by creating a sub property:



objOpts.custom.option4 = 'Option4'
objOpts.custom.option5 = 'Option5'


this way you could delete objOpts.custom and get done with it. Note that after this step you would have to recreate objOpts.custom = {}.



Moreover this way would also feel closer to OOP, since your public properties would easily be distinguishable from private ones.



If you are beginning with deleting objects in JavaScript, I'd like to point to to an excellently written article on the topic: http://perfectionkills.com/understanding-delete/



You could play around with the meta properties which allow you to protect properties from being deleted etc. (to create an even better coding flow for your case)



EDIT:



I'd like to add that instead of deleting and recreating the property, you could simply say objOpts.custom = {} which would release the option4 and option5 from memory (eventually, via Garbage Collection).


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

Total Points: 675
Total Questions: 86
Total Answers: 102

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
montana questions
Sat, Sep 19, 20, 00:00, 4 Years ago
Fri, Jan 31, 20, 00:00, 4 Years ago
Thu, Sep 12, 19, 00:00, 5 Years ago
;