AS3:如何简化Action Script 3 Code?

时间:2010-05-07 10:36:09

标签: actionscript-3 simplify simplification

这是我想要创建一个具有鼠标悬停效果的按钮时使用的示例:

    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);

为什么不起作用?

4 个答案:

答案 0 :(得分: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);

始终追求其他任何可读性。其次,

this.buttonExample.buttonMode = true; 

不会返回任何对象,因此您无法与任何内容进行交互。

答案 1 :(得分:4)

如果您经常使用该模式,您可以创建一个辅助函数:

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

然后在某处调用它:

setAsButton(this.buttonExample, myaction);

答案 2 :(得分: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(...);

如果分配的值是不可变的(例如truefalse,数字和字符串,那么非常小心,只能以这种方式链接分配,但数组或大多数其他对象),因为相同的对象将被分配给左侧的所有变量。如果值是不可变的,这无关紧要,但如果它是可变的,你可能会得到奇怪的结果,如下例所示:

 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(...);

它说b.buttonMode = b.useHandCursor = true但不添加.addEventListener(...)的原因是赋值表达式的值(例如b.buttonMode = true)是值赋值到左侧(例如true)。如果您添加.addEventListener(...),那么您实际上是在说true.addEventListener(...),这显然不是您想要的。换句话说

b.buttonMode = b.useHandCursor = false;

相当于

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

希望这也可以使上面提到的警告变得清晰。

答案 3 :(得分:0)

您可以使用with statement。但是我不鼓励你这样做,因为它会导致很多模糊和不清楚。

另外,您可以进行多项作业:

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

这有时很有用,但为了便于阅读,你不应该过度使用它。

格尔茨
back2dos