2011-11-19 143 views
0

有沒有辦法通過它的UID獲取對象,以便下面的代碼可以工作?如何通過其uid獲取對象?

當函數完成時,屬性「xxx」的值應該是「字符串2」而不是「字符串1」。

// Test class 
public function test():void { 
    this.xxx = "string one"; 
    foo.bar(this.xxx); 
    trace(this.xxx); // Prints: string two 
} 

// Foo class 
public function bar(value:*):void { 
    // ... What would I have to do here to get the property, not its value? 
    value = "string two"; 
} 

回答

0

如何使用方括號?我知道這不是OO的做法,但Action腳本支持它,它看起來像一個很好的選擇。

class Test { 
public var xxx:String; 

public function test():void { 
    this.xxx = "string one"; 
    foo.bar(this,"xxx"); // actual name of property as string ;litral 
    trace(this.xxx); // Prints: string two 
    } 
} 

class Foo { 
public function bar(test:*,prop:String):void { 
    //test could be from any class . 
    test[prop] = "string two"; 
    } 
} 

這應該可以做到。但是你需要確保哪個代碼調用「bar」方法傳遞一個有「xxx」屬性的有效對象,因爲這個代碼不再是類型安全的。

+0

這看起來不錯,我猜,它可以從CTRL +空間中受益。 – GxFlint

0

函數的參數(對變量的引用)不能改變。這不是一個指針。您可以爲其分配其他變量,但不會更改傳遞給該函數的參數。但是,您可以更改參數的屬性:

class Test { 
    public var xxx:String; 

    public function test():void { 
     this.xxx = "string one"; 
     foo.bar(this); 
     trace(this.xxx); // Prints: string two 
    } 
} 


class Foo { 
    public function bar(test:Test):void { 
     test.xxx = "string two"; 
    } 
} 

當然這個工作,類Foo必須知道Test,也更改的屬性。這使得一切都變得不那麼活躍,並且可能不是你想要的。這是一種您可以使用Interface的情況。或者,您可能想要堅持使用常規模式,如使用吸氣劑並將值分配給相應的屬性:

class Test { 
    public var xxx:String; 

    public function test():void { 
     this.xxx = "string one"; 
     this.xxx = foo.getValue(); 
     trace(this.xxx); // Prints: string two 
    } 
} 


class Foo { 
    public function getValue():String{ 
     return "string two"; 
    } 
} 
+0

但是我不能將指針的UID發送給函數,並將它形成實際的指針嗎?在我的情況下,沒有辦法使用接口,也必須在第二個函數內完成賦值。 – GxFlint

0

要得到一個屬性,最簡單的方法是將物業封裝成一個對象,把它傳遞給函數,然後檢索:

// Test class 
public function test():void { 
    var obj: Object = new Object(); 
    obj.variable = "string one"; 
    foo.bar(obj); 
    trace(obj.variable); // Prints: string two 
} 

// Foo class 
public function bar(value:Object):void { 
    value.variable = "string two"; 
} 

但是,你爲什麼要這麼做?這是在各方面都好得多隻是做xxx = foo.bar();

+0

我不能這樣做,它是我寫封裝RemoteObjects的一個小框架的一部分。所以「正確的方式」是行不通的。 – GxFlint

0

傳遞按值

當傳遞一個變量到變量被複制的功能。對變量進行的任何更改都不會在退出後反射回來。

傳遞通過引用

當傳遞變量成一個函數時,「指針」變量被傳遞。您對變量所做的任何更改都將被複制。

在AS3中,一切都通過引用,,除了 primitives(布爾,字符串,int,uint等),它們在幕後有特殊的運算符,使它們像傳遞值一樣行事。由於xxx是一個字符串,這就是發生了什麼。 (另外,字符串是不可變的;你不能改變它們的值)。

如何修復它(如其他人所說的):

  • 傳遞Test對象本身的bar()功能:bar(this);
  • 封裝xxx參數在它自己的對象和傳遞:bar({prop:this.xxx});
  • 已將bar()返回該值並將其設置爲:this.xxx = bar();
+0

看起來不錯,但仍然沒有達到我要找的。問題是'bar()'是異步的,所以它不能返回任何東西。所以我認爲@ arpit-agarwal的解決方案是唯一的出路。 – GxFlint

+0

答案更多地解釋*爲什麼它不起作用。真的只有3種方法來解決它。通過你上面發佈的代碼,'bar()'是同步的,所以返回應該工作,除非我失去了一些東西。只要回答誰先發布的答案:D – divillysausages