How do you remove objects?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mrjohn
    New Member
    • May 2009
    • 31

    How do you remove objects?

    Hey!

    I'm working on a javascript project which will run on a single html page, and I'm using lots of objects. The program will create new instances of these objects during runtime. However, for efficiency, I need a way to get rid of the old ones. Is there any way to do this?
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    by objects you mean elements?

    any html element can be cleared with the innerHTML() method. Just set it to an empty string.

    Comment

    • mrjohn
      New Member
      • May 2009
      • 31

      #3
      Ach, I'm sorry, I meant this sort of object
      [CODE=javascript]
      function spaceShip(hull, shields, weapons)
      {
      this.hull = hull;
      this.shields = shields;
      this.weapons = weapons;
      this.crew = 5;
      }
      var nightHawk = new spaceShip("Tita nium", 16, phasers);
      [/CODE]
      I'm not sure what it is called, but I was wondering how to remove instances of such an object.

      Comment

      • mrhoo
        Contributor
        • Jun 2006
        • 428

        #4
        If you declare your objects as globals with the var keyword, as in your example, you cannot delete them. The nearest you can get is to set them to undefined.

        Comment

        • mrjohn
          New Member
          • May 2009
          • 31

          #5
          Oh dear. That is a bit of a bummer. What if instead I put them in an array, like this?
          [CODE=javascript]
          var fleet = new Array(3);
          fleet[0] = new spaceShip("Iron ", 9, phasers);
          fleet[1] = new spaceShip("Tita nium", 13, phasers);
          fleet[2] = new spaceShip("Alum inum", 2, phasers);
          fleet.splice(1, 1);
          [/CODE]
          When splice is run, would the object be removed then? Or would it just be floating around somewhere?

          Comment

          • dmjpro
            Top Contributor
            • Jan 2007
            • 2476

            #6
            Object removing means .. you want to say your JS Engine to free up the memory(occupied by an instance) when the object no longer needed.
            Did you mean that?

            Comment

            • mrjohn
              New Member
              • May 2009
              • 31

              #7
              Yeah, thats what I meant.

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Where possible, use the delete operator.

                Comment

                • mrjohn
                  New Member
                  • May 2009
                  • 31

                  #9
                  Awesome! Thank you very much.

                  Comment

                  Working...