3 Replies Latest reply on Aug 10, 2009 7:22 AM by kglad

    Class property initialization

    Pāvils Jurjāns

      Hello,

       

      This costed me abut 4 hours of my life. Please tell me, what's going on (AS2, Flash CS4).

       

      Here's the test code:

       

      // Class

       

      class InitTest
      {
      private var a:Array = [];

      function InitTest()
      {
        test();
      }

      public function test()
      {
        trace("a.length="+a.length);
      }

      public function addItem()
      {
        a.push(1);
      }
      }

       

      // Code

       

      var it1 = new InitTest();
      it1.addItem();
      var it2 = new InitTest();

       

      // Output

       

      a.length=0
      a.length=1

       

      // End of test code

       

      Why on earth the private property a is already populated, when the second instance is initialized? The array property is now shared between the instances, like a static property. If I'd add to test code

       

      it2.addItem();
      it1.test();

       

      I get

       

      a.length=2

       

      Ok, I now found out that if I leave just  private var a:Array; in the declaration and do a = []; in the constructor, this works as expected. But what' s the problem with the test code above?

       

      -- Passiday.