문제

I tried to execute the following actionscript3 program and I am surprised of the result of the call to f() function. I was expecting that the result of f() was "1" or at least "undefined" but the "0" value does not makes any sense for me.

I will be pleased to have a good explanation of this behavior if you have one, or to know if you consider this behavior as "normal". I want to precise that I'm studying the behavior of Action Script programs in order to understand how the AVM2 really works and therefore I am not asking equivalent code to do the same thing. As a consequence if you have other tricky examples I am also interested.

package {
import flash.display.Sprite;

  public class S2 extends Sprite {
      public function f():* {
           return x;
       }      
       public static function fs():*{
           return x;
       }      
  }
}
var x:int = 1 ;
var a:S2 = new S2();
var g:Function = a.f;
var gs:Function = S2.fs;
trace("tracing(g)...:"+g()); //tracing(g)...:0
trace("tracing(gs)...:"+gs()); //tracing(gs)...:1

Note: I compiled this program with the following command line:

mxmlc -debug -static-link-runtime-shared-libraries=true -output S2.swf -- S2.as
도움이 되었습니까?

해결책

Your x variable exists in a different scope than the x you are returning from S2.f()

S2 extends Sprite, which in turn extends DisplayObject, which already has a x property.
This is what you are returning.

If you change the variable name to something like myX you will get an error a expected.

Doing this will change what is returned:

var a:S2 = new S2();
a.x = 10;
trace(a.f()); // will trace 10
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top