Reputation: 52
Ok, this is out of "academic interest" (although I'm thinking of using it somewhere). Suppose I have the following:
function f2 ()
{
delete Widget.f1;
Widget.f3 = function ()
{
console.log("This works.");
}
}
let Widget =
{
f1: function ()
{
f2();
}
}
console.log(Widget);
Widget.f1();
console.log(Widget);
Widget.f3();
So basically I call upon a method to remove itself from the object and be replaced with another method. It seems to work fine. So here are my two questions:
Is there a good (technical) reason why I should not do this?
From an "in the bowels of JavaScript" point of view, how does this work? Intuition would say that f1 remains "open" until it has been completed, which would mean that we delete a function that is still "open". Is the f2() call somehow "hoisted" out of it?
Cheers
Upvotes: 0
Views: 70
Reputation: 85132
Is there a good (technical) reason why I should not do this?
The main reason i would not use this is that it is confusing and likely to cause bugs when other developers (including future-BVDev) either don't notice that you're doing it, or don't understand why you're doing it.
From an "in the bowels of JavaScript" point of view, how does this work?
Widget.f1
is a reference to a function, it's not the function itself. So when you delete Widget.f1
, that reference is now gone, but the function continues to exist in memory. It also continues to exist on the current execution stack. If there are other references to the function, then it will continue to exist after the call stack has finished. On the other hand if this was the only reference to the function, then some time later, the garbage collector will run and free the memory that the function was taking up.
Upvotes: 1