[removed] Create and destroy class instance through class method

后端 未结 3 1196
抹茶落季
抹茶落季 2021-02-03 18:16

I\'m trying to figure out how to delete an object through a class method. I would like to be able to create a class that has a destroy method that releases the object from memor

3条回答
  •  醉话见心
    2021-02-03 18:31

    You can only manually delete properties of objects. Thus:

    var container = {};
    
    container.instance = new class();
    
    delete container.instance;
    

    However, this won't work on any other pointers. Therefore:

    var container = {};
    
    container.instance = new class();
    
    var pointer = container.instance;
    
    delete pointer; // false ( ie attempt to delete failed )
    

    Furthermore:

    delete container.instance; // true ( ie attempt to delete succeeded, but... )
    
    pointer; // class { destroy: function(){} }
    

    So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

    A manually specified destroy method could unbind any event listeners. Something like:

    function class(){
      this.properties = { /**/ }
    
      function handler(){ /**/ }
    
      something.addEventListener( 'event', handler, false );
    
      this.destroy = function(){
        something.removeEventListener( 'event', handler );
      }
    }
    

提交回复
热议问题