Skip to content

with() Problem/Bug

Categories: Flash

Table of Contents

This is yet another bug I found while doing some Flash-dev, it has to do with the with() statement.
If you use with(this){…} it will give you erratic/unpredicted behavior, for instance take this code:

ob = {};
ob.test = function() {
	with(this) {
		__x = 1;
		trace("test: inside: "+__x);
	}
	
	trace("test: outside: "+this.__x);
}

ob.test();

You would think that output would look like this:

test: inside: 1
test: outside: 1

But, instead it comes out as:

test: inside: 1
test: outside: undefined

Seems as though Flash does not allow you to set variables when using this in a with() statement. You can get the .fla i used to make the test cases for this bug here.
Thanks Macromedia for wasting another hour of my time! 😛

2 responses to “with() Problem/Bug

  1. You could have saved yourself an hour by reading the reference information for the with() statement…lol.

    “To set a variable inside a with statement, you must have declared the variable outside the with statement, or you must enter the full path to the Timeline on which you want the variable to live. If you set a variable in a with statement without declaring it, the with statement will look for the value according to the scope chain. If the variable doesn’t already exist, the new value will be set on the Timeline from which the with statement was called.”

    BTW: This works…

    with (this) {
    this.__x = 1;
    trace(“inside”+__x);
    }
    trace(“outside”+this.__x);

    Because of the scope of how you define the variables. Since __x isn’t defined, using a with(this) statement doesn’t define it within the object itself it is instead defining it within the timeline scope of the ‘this’ object.

    Example in your test file…

    You have…

    ob3.test2 = function() {
    with (this) {
    __x = 50;
    trace(“test2: inside “+__x);
    }
    trace(“test2: outside “+this.__x);
    };

    Now, remove __x = 50 from that statement. You will see it will return 1 now. Because you set it to 1 in the first object test() prototype.

    Bah, I’m just babbling, but in essense, it isn’t a bug at all, it’s just how Flash works with the with() statement.

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep in Touch

Subscribe to my email list to keep in touch. I’ll send you new blog posts and other thoughts.