— Shang Liang

Funny things about static const in ActionScript 3

package
{
	public class FunnyStaticConst
	{
		// mess around with the sequence but it still works
		private static const num1:int = num2;
		private static const num2:int = 100;
		// a constant object?
		private static const BASE:Object = {name:'banana', color:'yellow'};

		// constructor
		public function FunnyStaticConst()
		{
			//let's change the "constant"
			BASE.name='apple';
			BASE.color=red';
			trace(BASE.name,BASE.color);
			// the result is "apple,red"
		}
	}

}

8 comments
  1. Dev says: August 22, 20081:22 pm

    It’s really funny !

    Object is a dynamic class, so its properties can be added at run time. May be this situation happens to any other dynamic classes as well. Let’s try it on.

  2. Eric says: August 23, 20083:14 am

    Actually, I think this makes a lot of sense.

    FunnyStaticConst:BASE is a static constant, not it’s members, so of course you should be able to change them. You should not, however be allowed to redefine FunnyStaticConst:BASE altogether (such as FunnyStaticConst:BASE = {who:’me’, when:’now’}).

    BTW: Either your wp spam blocker doesn’t like Safari, or my copy of Safari is jacked up.

  3. 5566 says: August 23, 20084:33 am

    I thought only numbers, strings etc can be a constant. After giving some more thoughts, I realize a constant object is a constant pointer pointing to something can be changed from time to time.

  4. [...] by wolsab on Tue 14-10-2008 org.as3s.Tween at AS3S.ORG Saved by saaipuntnl on Mon 13-10-2008 Funny things about static const in ActionScript 3 Saved by freckle73 on Mon 13-10-2008 ActionScriptCheatSheet.com – Adobe Flex, Adobe AIR, [...]

  5. tamt says: February 6, 20099:23 pm

    i think it’s not funny, it should be that

  6. Jev says: April 8, 20106:24 am

    If as3 is like most other languages, this is because any variable of a non-primitive (object) type only stores the reference to the actual object (i.e. the memory address of the object data). So the const is still constant because you cant set the BASE const to point to a different object, as you can with a normal var, such as:

    var obj1:Object = {name:’banana’, color:’yellow’};
    var obj2:Object = obj1;
    obj2.name = ‘apple’;
    trace(obj1.name); //output is apple

  7. CCER says: February 8, 20114:59 pm

    The reference to the object BASE is constant and can’t be redefined to point to another Object. It has no effect on the object’s members.

  8. gvd says: October 24, 20111:26 pm

    every other language with constants have exactly same behavior, so it’s exactly right and not funny.

Submit comment

For spam filtering purposes, please copy the number 8827 to the field below: