你不要那样做。动态是允许您添加任何尚未声明的临时属性,而不是覆盖已声明的函数。不要将动态与抽象混淆。
尝试这样的事情
public class Bullet extends Sprite{
public var speedX = 5;
public var speedY = 5;
public function update():void{
x += speedX;
y += speedY;
}
}
public class BulletFactory{
public static function getFastBullet():Bullet{
var result:Bullet = new Bullet();
result.speedX = result.speedY = 10;
return result;
}
}
根据您的喜好调整 speedX/speedY 的公共/私人可见性。
另一方面,如果您想尽可能从字面意义上“动态地覆盖一个函数”,那么总会有这个(这是hacky但有效)。
public class AbstractBullet extends Sprite{
public var update:Function; // <- Notice that function is just a variable here.
}
然后在您的子弹工厂中,您可以临时分配更新功能。请注意,这不太“安全”,因为您失去了所有类型安全的概念,因为更新不再具有集合签名。在调用它之前,您还必须确保它存在。如果要避免编译器警告,则必须显式地进行空检查。
var f:Function;
// this is fine.
// it's particularly safe if
// f is a declared variable of type
// Function.
if(f != null) f();
// this is also fine,
// and is preffered if f is NOT
// a defined variable but instead
// a dynamically created (and therefore
// untyped) variable of a dynamic object.
// You would not want to "call" something
// that is not a function, after all.
if(f is Function) f();
// but this gives a warning
// even though the code works
// correctly at runtime.
if(f) f();