as3中有一个Point(flash.geom.Point)类 我想将方法添加到类Point(例如convertToStagePointMyMethod()),我想通过使用
来调用此方法var a:Point=new Point();
a.convertToStagePointMyMethod()
为了将此方法添加到类Point,我该怎么办?没有继承就有可能。我想像.NET中的“部分”类一样使用它
答案 0 :(得分:6)
以下是使用prototype的简短示例:
Point.prototype.foo = function (arg:String):void{
trace("foo called");//foo called
trace("arg",arg);//this is a test
trace("x",this.x);//7
trace("y",this.y);//54
};
var p:Point = new Point(7,54);
p["foo"]("this is a test");
这是在不扩展课程的情况下执行此操作的唯一方法。
另请注意,如果您尝试使用p.foo("test")
,编译器将无法在严格模式下编译,这就是我在我的示例中编写p["foo"]("test")
的原因。
答案 1 :(得分:2)
除了使用OXMO456的非常酷的例子(以前从未见过,真的很酷),你需要使用继承或组合。如果类是“动态”类,如MovieClip类或URLVariables类,您不必担心,但Point不是动态的。
您可以通过以下方式创建自己的动态类:
dynamic public class MyClass {...}
答案 2 :(得分:1)
制作自己的积分课程
package
{
import flash.geom.Point;
/**
* ...
* @author Jesse Nicholson
*/
public class MyPoint extends Point
{
public function MyPoint(positionX:Number, positionY:Number) {
//Pass the constructor args to the super class, the Point class since it requires these params in it's constructor
super(positionX, positionY);
}
public function convertToStagePointMyMethod():Number {
//Do my calculations here
var someNumber:Number = 10;
return someNumer;
//OR return a Point OR do whatever the hell you want here, you're the boss of your own point class
}
}
}
这只是你做事的方式。当你有一个你想要使用但只是添加的现有类时,将它扩展到一个新类并做到这一点。这是面向对象编程和“最佳实践”方法的基本思想。
答案 3 :(得分:1)
我通常创建独立的实用程序函数,而不是扩展一个类,如下所示:
package com.example.utils
{
public function doSomethingToPoint(p:Point):void
{
//do something
}
}
将它放在名为doSomethingToPoint.as的文件中,你就可以了。它的工作方式与内置的包级功能类似flash.net.navigateToURL
。只需直接导入并使用该功能。
import com.example.utils.doSomethingToPoint;
var p:Point = new Point();
doSomethingToPoint(p)
或者,您可以创建一个包含多个相关静态函数的实用程序类,如下所示:
package com.example.utils
{
public class PointUtil
{
public static function doSomethingToPoint(p:Point):void
{
//do something
}
//other functions here
}
}
你可以使用这个类及其函数:
import com.example.utils.PointUtil;
PointUtil.doSomethingToPoint(p);
就个人而言,我更喜欢创建独立的函数,以便我的项目不需要编译实际上没有在任何地方使用的额外静态函数,但每个人都有自己的偏好。