Destroy 'this' with Javascript?

前端 未结 1 1647
忘了有多久
忘了有多久 2021-01-24 08:47

How do I destroy \'this\' within a function so that I destroy the instance of a function from within the function. If this is not possible with pure javascript. Is this possible

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 09:00

    You cannot destroy this in javascript and even trying to do so runs counter to how things are garbage collected in javascript. Also, you cannot assign to this in javascript.

    You do NOT manually free things in javascript. Instead, you clear all references to an object in javascript and when NO other code has a reference to an object in javascript, THEN and only then will the garbage collector free it.

    Since javascript does not allow you to assign to the this pointer, when you're in a function that has this set to a particular object, you simply can't cause that object to be freed in any way at that moment. You can make sure that no other objects have a reference to your object and then, when this method finishes, if nothing else has a reference to the object, then it will be freed by the garbage collector.

    Memory management in a garbage collected system is completely different than in non-garbage collected languages. You don't free things yourself. You clear references to things so that the GC can then clean up those objects at some later time if there are no other references to them.

    Here's an example. Supposed you have this object with a property stored in a global variable:

    // declare global object and add property to it
    var myGlobalObject = {};
    myGlobalObject.greeting = "Hello";
    

    You don't ever free that global variable explicitly, but if you want the object that it points to to be freed by the garbage collector, then you just clear the reference to the object:

    myGlobalObject = null;
    

    Then, the GC will see that there is no longer any code that has a reference to the object that myGlobalObject used to point to and since that object is now unreachable by any code, it will be freed by the GC.

    0 讨论(0)
提交回复
热议问题