我以为我在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])); }
在这一点上,我认为这mySoundArray[0]
将引用相同的对象myAmbientSound
; 但是,访问myAmbientSound
会抛出空指针异常,同时mySoundArray[0]
按预期工作并引用一个Sound
对象.我在这里误解了什么?
它更像是java引用变量而不是C指针.
var myAmbientSound:Sound; var myPeriodicSound:Sound; var myOccasionalSound:Sound; //these variables are not initialized and hence contain null values
现在,您创建一个包含这些变量的当前值(null)的数组
var mySoundArray:Array = [myAmbientSound, myPeriodicSound, myOccasionalSound];
该数组现在包含三个空值[null, null, null]
,而不是Sound
您希望它包含的三个指向对象的指针.
现在,当您调用时,会创建mySoundArray[0] = new Sound();
一个新Sound
对象并将其地址分配给该数组的第一个位置 - 它不会修改该myAmbientSound
变量.