开发者

Choosing a Class Dynamically in Actionscript 3

开发者 https://www.devze.com 2022-12-11 20:46 出处:网络
I have a line of code like this: var myObj:[SomeClass] = new [SomeClass](); I want to choose which class this object will belong to randomly at开发者_如何学Go runtime. Is there a way to do this in

I have a line of code like this:

var myObj:[SomeClass] = new [SomeClass]();

I want to choose which class this object will belong to randomly at开发者_如何学Go runtime. Is there a way to do this in Actionscript 3?


I don't know how well this would fly in AS3, but in JS, I'd use

var classes = [foo, bar, baz];
var myObj = new_(classes[random() % 3])();

maybe it'd work in AS3 too?

new_ is part of Zeta (http://codex.sigpipe.cz/zeta/docs/reference.rest#new-cls), random() is pulled from thin air.


Here comes Object Oriented Programming:

Declare your variable's type as a common super class's type (or an interface) and extend (or implement) all the possible classes from that super class (or interface).

public class MyType
{
}
public class Type1 extends MyType
{
}
public class Type2 extends MyType
{
}
public class Type3 extends MyType
{
}

var something:MyType;
//Now you can do
something = new Type1();
something = new Type2();
something = new Type3();

Here is a sample using interfaces:

public interface MyType
{
}
public class Type1 implements MyType
{
}
public class Type2 implements MyType
{
}
public class Type3 implements MyType
{
}


I think you should be able to do something like:

var classes:Array = [Class1, Class2, Class3];
var obj:Obj = new classes[0];

Each class will probably have to implement a shared interface to make it useful. So it would look something like:

var classes:Array = [Class1, Class2, Class3];
var obj:IInterface = (new classes[0]) as IInterface;


I suggest the following if you have several classes: Class1, Class2, Class3 who all extend AbstractItem

var itemClass:Class = getDefinitionByName("com.packagename.Class" + Math.floor(Math.random()*3 +1)) as Class;
var item:AbstractItem = new itemClass();


This is what just somebody's answer would look like in proper AS3 syntax.

var classes:Array = [Foo, Bar, Baz];
var myObj:YourSuperclass = new classes[int(Math.random() * classes.length)];

If the classes do not have a common superclass you can keep myObj untyped.


I don't think there is any direct way to do this. But you can try this thing.

var funcArray:Array = new Array();

public function getObjClass1():Class1 {
  return new Class1();
}
...
...
public function getObjClassN():ClassN {
  return new ClassN();
}
//add all functions to funcArray array
public function addFunctions():void {
  funcArray.push(getObjClass1);
  ...
  funcArray.push(getObjClassN);
}

public function getRandomObject():* {
  return funcArray\[Math.floor(Math.Random() * funcArray.length)\]();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消