Flashmx2004系列教程〈三〉ActionScript 2.0--动态类VS静

动态类允许动态的对类进行扩展(例如允许加入新的属性或方法)。象Jscript.NET程序中这种方式称为expando,如果类不是动态类(象Math类)用户不能加入新的属性和方法。而在as1中这其实是很平常的事。就象下面这样为MOVIECLIP加入新的属性和方法:

movieClip.protoType.someNewMethed=function(){

   一些方法;

}

在as2中这种扩展方式是不允许的。然而我可能通过创建子类的方式加入新的属性和方法。

下面的例子是我们要扩展静态类Math中的Max()方法.我们要新将其扩展为在一些数中求出最大的数而不是原先那样只限定在两个数中求出最大的数。

dynamic class Math2 extends Math {
   // store a reference to Math.max()
   private static var oMax:Function = Math.max;
// static class cannot be instantiated private function Math2() {} // override Math.max(), support any number of arguments public static function max():Number { var a:Array = arguments; var n:Number = a.length; if (n > 2) { var m:Number = oMax(a[n-2],a[n-1]); // remove two elements from the end of the array; // could use 'a.length -= 2' as a shortcut as well a.pop(); a.pop(); a.push(m); return Number(max.apply(null, a)); } else if (n == 2) { return oMax(a[0],a[1]); } else if (n == 1) { return a[0]; } else { return oMax(); } } }

不象原有的类那样,现在我们已经对其MAX()方法进行了扩展将其变成了动态类。并且形成了新的类名为math2.

现在可以试一下了。

trace(Math2.max(70,6,3,12,82,9,28,5));