What's the better way to clear an object:
Write a method inside the class that clears all the members of the class: MyObject.Clear();
Inside my code, in the business logic, null
the object: MyObject = null;
Use a for..in loop to clear an object and delete all its properties. The loop will iterate over all the enumerable properties in the object. On each iteration, use the delete operator to delete the current property. Copied!
The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.
The _. omit function takes your object and an array of keys that you want to remove and returns a new object with all the properties of the original object except those mentioned in the array. This is a neat way of removing keys as using this you get a new object and the original object remains untouched.
They do different things. Setting a variable to null does nothing to the object itself. It may mean that the object is now eligible for garbage collection, but it will make no difference if there are other "live" reference to the same object.
What should you do? Well, it entirely depends on your situation. If you have lots of different places with reference to the same object, and they should all see the "clearance", then modify the object. If you just need one variable to refer to a different object or no object at all, just change the value of the variable.
The important thing is to know the difference between the two - be very aware that the value of a variable is never an object... it's either a reference or a value type value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With