2009-07-07 36 views
0

我有這個叫市小班,簡單地保存有關城市的一些信息,那就是:初始化引用類型的函數之外在ActionScript 2

class com.weatherwidget.City { 
    var zipCode:String; 
    var forecastText:Array = new Array(5); 
} 

當我有城市的數組,我改變其中一個城市的預測文本會改變所有城市的預測文本。

例如:

import com.weatherwidget.City; 

var arr:Array = new Array(); 
arr.push(new City()); 
arr.push(new City()); 

arr[0].forecastText[0] = "Cloudy"; 
trace(arr[0].forecastText[0]); 
trace(arr[1].forecastText[0]); 

將具有以下輸出:

Cloudy 
Cloudy 

儘管我只改的常用3 [0] .forecastText [0]。我想我一定是誤解的東西有關數組中的對象爲ActionScript 2

+0

如果任何人都可以對這個問題提出一個更好的問題名稱請讓我知道。 – Anton 2009-07-07 17:03:47

+0

接受的答案解釋了爲什麼發生這種情況,我的答案使它正常工作。 – Anton 2009-08-04 20:27:52

回答

1

很好的理由...嗯...有點複雜,解釋...

好嗎?ActionScript是prototype-oriented,因爲是ECMA-腳本...類只是一個語法糖的引入動作2(這在AS3再次改變,但是這是一個不同的主題)...

,所以如果這是原代碼:

class com.weatherwidget.City { 
    var zipCode:String; 
    var forecastText:Array = new Array(5); 
} 

那麼這就是,到底發生了什麼:

//all classes get stuffed into _global, with packages being a property path: 
if (_global.com == undefined) _global.com = {}; 
if (_global.com.weatherwidget == undefined) _global.com.weatherwidget = {}; 
//and the actual definition: 
_global.com.weatherwidget.City = function() {}; 
_global.com.weatherwidget.City.prototype = { forecastText:new Array(5) } 

City原型對象,用作原型的City實例中,有一個稱爲forecastText屬性,它是長度爲5的Array ...等等的City實例仰視forecastText時,它不能直接找到並將在原型鏈中查找...它會在實例的原型中找到...因此,所有實例共享Array ...

區別在於,第二個示例獲取翻譯爲:

//same thing here: 
if (_global.com == undefined) _global.com = {}; 
if (_global.com.weatherwidget == undefined) _global.com.weatherwidget = {}; 
//and the actual definition this time: 
_global.com.weatherwidget.City = function() { this.forecastText = new Array(5); }; 
_global.com.weatherwidget.City.prototype = {} 

,你可能已經注意到,聲明成員只是一個編譯時的事情......如果沒有被分配給他們,他們根本不會在運行時存在...

好,這explenation要求,你要麼知道的JavaScript或ActionScript 1一點點,但我希望它可以幫助...

格爾茨

back2dos

1

的陣列需要某種原因構造函數或所有城市物體的內部被初始化將指向同一個數組。所以城市類應該是這樣的:

class com.weatherwidget.City { 
    var zipCode:String; 
    var forecastIcons:Array; 

    function City() { 
     forecastIcons = new Array(5); 
    } 
} 

我仍然不知道爲什麼它必須在構造函數初始化,因爲數組是不是靜態的,所以如果有人想解釋這一點,將不勝感激。