4 ms·
The "free" function as written won't work. When using Object.defineProperty if "configurable" is not set, the default is false (at least in Firefox, I don't r
by M1573RMU74710N 15y ago
The "free" function as written won't work.
When using Object.defineProperty if "configurable" is not set, the default is false (at least in Firefox, I don't recall what the spec says but I think it's just toBoolean whatever calling [[getownproperty]] "configurable" on the description object is, which would default to false), meaning the property cannot be deleted (or redefined).
(I'd also note not all browsers support defineProperty)
I'd also note to readers that the "delete" operator just removes a property name from an objects own property list, and has little to do with garbage collection directly. In this case I think the goal is to get rid of the closure created which handles the property, which I think would work (if the previous error is fixed), but I'm not familiar enough with JS engine internals to know.
I would probably just redefine the property to be "null". Once the property is null'd out, there's probably not much benefit to also removing the property from the property list.
With it null'd out as opposed to deleted you'd also not have to worry about an Object up the prototype chain punching through, and might be desirable in other ways.
Also note that this will not necessarily free up whatever was stored in the "pointer". I don't think that was the author's intention, but I just wanted to make that clear to readers.
If you did:
var foo = {};
foo = $(foo);
bar = $[foo];
$.free(foo);
The object created on the first line would not be garbage collected after free is called because bar now contains a reference to it.
If your goal was to clear up whatever was stored in "val" as well as the closure itself, you'd have to first set the property to null (to take care of "val"), and then redefine the property to null (to take care of the closure).
Of course, the biggest problem here is that this is pointless.
They are storing the value in a closure, but since they just expose the closure with get and set methods, they could just skip it all and us an Array.
- adrusi 15y agoYes I suppose `configurable` should be enabled. The reason I used delete instead of setting to null is that null is considered just as important a value as any other and if you had an outrageous number of nulls, it could consume a noticeable amount of memory. `free` only releases the data stored in the global pointer object, not the original variable itself, that's not possible. I don't know how many time's I've had to say this, but this was never intended to actually be used, just as a proof of concept.