AS3 - 基类可以创建与其自己的实例相同的扩展类的新实例吗?

时间:2012-11-23 11:30:02

标签: actionscript-3 oop

MyCollection是一个可能有很多扩展类的通用类,它可以创建一个新实例来使用任何类型的实例吗?

public class MyCollection extends Array {
    public function getUnionWith(someCollection:MyCollection):MyCollection {
        //can I create and return a new instance of the same class as this instance here? 
        //(so in this example: a new ViewCollection or ItemCollection)
    }
}
public class ItemCollection extends MyCollection { }
public class ViewCollection extends MyCollection { }

...

//so that this will work:
var viewsOccuringInBoth:ViewCollection = viewCollection1.getUnionWith(viewCollection2) as ViewCollection;
//but this will work too!
var itemsOccuringInBoth:ItemCollection = itemCollection1.getUnionWith(itemCollection2) as ItemCollection;

1 个答案:

答案 0 :(得分:1)

我认为类似于描述的here可以在你的getUnionWith方法中使用:

public function getUnionWith(someCollection:MyCollection):MyCollection
{
    var clone:MyCollection = new (this as Object).constructor();//MUST NOT have any required arguments in constructor otherwise it will throw error

    //here do merging

    return clone;

}