2010-05-07 32 views
0

這裏,我已經當我想創建一個鼠標懸停效果的按鈕使用例如:AS3:如何簡化動作腳本3代碼?

this.buttonExample.buttonMode = true; 
    this.buttonExample.useHandCursor = true; 
    this.buttonExample.addEventListener(MouseEvent.CLICK,myaction); 

我新的AS3 - 有什麼辦法,來簡化這個代碼是這樣的:

this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction); 

它爲什麼不起作用?

+0

它爲什麼要工作? – sharvey 2010-05-10 15:47:39

+0

我同意s.harvey,你不能只是彌補的東西,並期望它會工作。 – davr 2010-05-11 01:45:51

回答

4

它已經很簡單了。首先

this.buttonExample.buttonMode = true; 
this.buttonExample.useHandCursor = true; 
this.buttonExample.addEventListener(MouseEvent.CLICK,myaction) 

this.buttonExample.buttonMode = true;.useHandCursor = true;.addEventListener(MouseEvent.CLICK,myaction); 

更可讀總是去readbility超過其他任何東西。其次,

this.buttonExample.buttonMode = true; 

不返回一個對象,所以你不能與任何東西交互。

4

如果您正在使用的模式有很多,你可以做一個輔助函數:

public function setAsButton(button:Sprite, clickHandler:Function):void { 
    button.buttonMode = button.userHandCursor = true; 
    button.addEventListener(MouseEvent.CLICK, clickHandler); 
} 

然後地方叫它:

setAsButton(this.buttonExample, myaction); 
+1

你可以省略'this'。 – bitc 2010-05-07 10:53:22

+0

我會更進一步,並創建一個類 var btn:Btn = new Btn(btnExample); btn.addEventListener(... – maxmc 2010-05-07 11:31:38

0

可以使用with statement。但我不鼓勵你這樣做,因爲它會導致很多模糊和不清楚。

也,你可以有多個任務:

this.buttonExample.buttonMode = this.buttonExample.useHandCursor = true; 

這有時是有用的,但是可讀性的原因,你不應該過度使用它。

格爾茨
back2dos

+0

我也讀過AS3中的「with」有性能問題 – Shiki 2010-05-07 10:53:40

+0

@Shiki:它不應該以嚴格類型的方式訪問屬性,否則屬性分辨率變得相當昂貴當然, – back2dos 2010-05-07 11:22:02

+0

你的意思是「以嚴格類型的方式訪問」 – Rihards 2010-11-09 13:56:24

3

如果你覺得一遍一遍輸入this.buttonExample是過於重複,僅僅是對象賦值給一個變量並使用該變量在語句的其餘部分:

var b : Button = this.buttonExample; 
b.buttonMode = true; 
b.useHandCursor = true; 
b.addEventListener(...); 

正如其他人所說,還有with聲明,但它的使用是不鼓勵的,因爲它使代碼更難以閱讀,並可能導致奇怪的結果:

with (this.buttonExample) { 
    buttonMode = true; 
    useHandCursor = true; 
    addEventListener(...); 
} 

你可以,當然,結合這些建議與其他招數,比如鏈接分配:

var b : Button = this.buttonExample; 
b.buttonMode = b.useHandCursor = true; 
b.addEventListener(...); 

非常小心,僅鏈作業以這種方式如果指定的值是不變(例如true,false,數字和字符串,但而不是數組或大多數其他對象),因爲相同的對象將被分配給左側的所有變量。如果該值是不可變的這並不重要,但如果它是可變的,你可以用怪異的結果結束了,像這樣的例子:

a = b = [ ]; 
a.push(1); 
b.push(2); 
trace(a); // outputs 1, 2 
trace(b); // also outputs 1, 2 

其原因的結果是,ab均引用同樣的數組,因爲數組是可變的,所以訪問對象的方式並不重要,它仍然會被改變。 ab不僅僅因爲它們是不同的變量而引用不同的數組。

你可能認爲你可以做下面的事情,但它會而不是的工作。

// this will NOT work 
var b : Button = this.buttonExample; 
(b.buttonMode = b.useHandCursor = true).addEventListener(...); 

爲什麼它說​​,但不添加.addEventListener(...)是一個賦值表達式(例如b.buttonMode = true)的值是分配給左側(例如true)的值的原因。如果你添加.addEventListener(...)到你基本上說的true.addEventListener(...),這顯然不是你想要的。換句話說

b.buttonMode = b.useHandCursor = false; 

相當於

b.useHandCursor = false; 
b.buttonMode = b.useHandCursor; 

其中應該有希望也會讓上面提到平原的注意事項。