动作脚本3 - 参考与价值

jus*_*ach 4 flash reference actionscript-3

我以为我在AS3中有参考,但以下行为让我困惑:

// declarations for named individual reference later on
var myAmbientSound:Sound;
var myAmbientSoundLocation:String = "http://ambient_sound_location";

var myPeriodicSound:Sound;
var myPeriodicSoundLocation:String = "http://periodic_sound_location";

var myOccasionalSound:Sound;
var myOccasionalSoundLocation:String = "http://occasional_sound_location";

// for iterating through initialization routines
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
var mySoundLocation:Array = [myAmbientSoundLocation, myPeriodicSoundLocation, myOccasionalSoundLocation];

// iterate through the array and initialize
for(var i:int = 0; i < mySoundArray.length; i++) {
    mySoundArray[i] = new Sound();
    mySoundArray[i].load(new URLRequest(mySoundLocation[i]));
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我认为这mySoundArray[0]将引用相同的对象myAmbientSound; 但是,访问myAmbientSound会抛出空指针异常,同时mySoundArray[0]按预期工作并引用一个Sound对象.我在这里误解了什么?

Ama*_*osh 7

它更像是java引用变量而不是C指针.

var myAmbientSound:Sound;
var myPeriodicSound:Sound;
var myOccasionalSound:Sound;
//these variables are not initialized and hence contain null values
Run Code Online (Sandbox Code Playgroud)

现在,您创建一个包含这些变量的当前值(null)的数组

var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
Run Code Online (Sandbox Code Playgroud)

该数组现在包含三个空值[null, null, null],而不是Sound您希望它包含的三个指向对象的指针.

现在,当您调用时,会创建mySoundArray[0] = new Sound();一个新Sound对象并将其地址分配给该数组的第一个位置 - 它不会修改该myAmbientSound变量.

  • @Tyn我不以为然.对于类型变量,"对于除`Boolean`,`Number`,`int`和`uint`之外的数据类型,任何未初始化变量的默认值为null.这适用于ActionScript 3.0定义的所有类,以及您创建的任何自定义类." http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9d.html (2认同)