AS3 |如何使用var作为名称?

时间:2014-02-28 11:10:03

标签: actionscript-3 actionscript

我的代码是:

for (var i:int=1; i <= 12; i++) {
    MovieClip(getChildByName('mouse' + '_' + i)).addEventListener(MouseEvent.CLICK, chooseTool);
}

function chooseTool(e:MouseEvent):void {
    Mouse.hide();

    var cursor:MovieClip = new "here is e.target.name"();
    addChild(cursor);

    stage.addEventListener(MouseEvent.MOUSE_MOVE, follow);
}

function follow(e:MouseEvent):void {
    cursor.x=mouseX;
    cursor.y=mouseY;
}

如何使用“e.target.name”作为名称? 应该变成这样的东西:
1)单击名称为mouse_4​​的按钮 2)函数chooseTool创建名为mouse_4​​()的新MovieClip;
例如:var cursor:MovieClip = new mouse_4();

3 个答案:

答案 0 :(得分:1)

你不能这样做。这不是真正的名称将是一个新的类/类型。解决方案是扩展MovieClip并将该名称作为参数传递。我不知道你想要实现什么,但这是一个很好的开始。

class MyClip extends MovieClip 
{
    public var name:String="";
    public function MyClip(name:String) 
    {
        super();
    this.name=name;
    }
} 
}

代码看起来像这样,您可以在此类中添加与此类型相关的所有逻辑。

答案 1 :(得分:1)

你不能像这个新的“e.target.name”()一样实例化; 但是如果你想参考目标,你可以试试这个。

var cursor:MovieClip = e.target为MovieClip;

您无法修改游标的名称属性。

答案 2 :(得分:1)

您可以使用getDefinitionByNameAdobe documentation: getDefinitionByName

来完成此操作
for (var i:int=1; i <= 12; i++) {
    MovieClip(getChildByName('mouse' + '_' + i)).addEventListener(MouseEvent.CLICK, chooseTool);
}

function chooseTool(e:MouseEvent):void {
    Mouse.hide();

    var o:Object = getDefinitionByName(e.target.name);
        // ^ Gets a reference to the class object based on a string

    if(o == null) throw new Error("Unable to find class " + e.target.name);

    var c:Class = o as Class;
    var cursor:MovieClip = new c() as MovieClip;
    addChild(cursor);

    stage.addEventListener(MouseEvent.MOUSE_MOVE, follow);
}

function follow(e:MouseEvent):void {
    cursor.x=mouseX;
    cursor.y=mouseY;
}

但这种结构感觉非常糟糕。相反,我会使用工厂方法(Factory pattern on Wikipedia

for (var i:int=1; i <= 12; i++) {
    MovieClip(getChildByName('mouse' + '_' + i)).addEventListener(MouseEvent.CLICK, chooseTool);
}

function chooseTool(e:MouseEvent):void {
    Mouse.hide();

    var cursor:MovieClip = getCursor(e.target);
    addChild(cursor);

    stage.addEventListener(MouseEvent.MOUSE_MOVE, follow);
}

function follow(e:MouseEvent):void {
    cursor.x=mouseX;
    cursor.y=mouseY;
}

function getCursor(target:MovieClip):MovieClip
{
    switch(target.name)
    {
        case "cursor_4":
            return new cursor_4();

        default:
            return new default_mouse();
    }
}