动作脚本3 - “错误#1006:startDrag不是一个函数”

时间:2012-02-24 09:35:22

标签: actionscript-3

我正在编写拖动机制的代码,在开始拖动操作之前调用等待一小段时间。

但是我在mouseDownHandler()函数中收到此错误消息。

TypeError: Error #1006: startDrag is not a function.
    at Function/<anonymous>()[C:\blahblah_8216\bobo\flex2\src\ui\map\WorldMap.as:105]
    at Function/http://adobe.com/AS3/2006/builtin::apply()
    at SetIntervalTimer/onTimer()
    at flash.utils::Timer/_timerDispatch()
    at flash.utils::Timer/tick()

我通过声明

的克隆变量 _me 来稍微更改代码,从而找到了解决方案
 private var _me:WorldMap;

在构造函数

中实例化它
 public function WorldMap(){
     _me = this;
 }

在下面的代码中用 _me 替换可以正常运行

代码

    public var dragInProgress:Boolean = false;
    private var dragTime:int = 100;
    private var dragInProgressInt:int;




     private function mouseDownHandler(event:MouseEvent):void {
        trace(this.name," mouse down ",getTimer());

        dragInProgressInt = setTimeout(function():void
        {
            dragInProgress = true;

            this.startDrag(false,new Rectangle(Config.GAME_SCREEN_WIDTH - Config.FULL_GAME_SCREEN_WIDTH,
                Config.GAME_SCREEN_HEIGHT - Config.FULL_GAME_SCREEN_HEIGHT,
                Config.FULL_GAME_SCREEN_WIDTH - Config.GAME_SCREEN_WIDTH,
                Config.FULL_GAME_SCREEN_HEIGHT - Config.GAME_SCREEN_HEIGHT)); 
        }, dragTime);

    }



    private function mouseUpHandler(event:MouseEvent):void {

        clearTimeout(dragInProgressInt);

        setTimeout(function():void
        {
            dragInProgress = false;
            this.stopDrag();

        }, 1);

谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:1)

当你使用'this'时startDrag失败的原因是因为你是在'匿名函数'中调用它,这意味着'this'关键字将不再引用主类而是引用函数定义。 “匿名函数”基本上是一个未绑定到特定类read more here的函数。

完成您想要做的事情的另一种方法如下所示:

    public var dragInProgress:Boolean = false;
    private var dragTime:int = 100;
    private var dragInProgressInt:int;




     private function mouseDownHandler(event:MouseEvent):void {
        trace(this.name," mouse down ",getTimer());

        dragInProgressInt = setTimeout(mouseDownFinished, dragTime);

    }



    private function mouseUpHandler(event:MouseEvent):void {

        clearTimeout(dragInProgressInt);

        setTimeout(mouseUpFinished, 1);
    }


   private function mouseDownFinished():void
   {
       dragInProgress = true;

       this.startDrag(false,new Rectangle(Config.GAME_SCREEN_WIDTH - Config.FULL_GAME_SCREEN_WIDTH,
           Config.GAME_SCREEN_HEIGHT - Config.FULL_GAME_SCREEN_HEIGHT,
           Config.FULL_GAME_SCREEN_WIDTH - Config.GAME_SCREEN_WIDTH,
           Config.FULL_GAME_SCREEN_HEIGHT - Config.GAME_SCREEN_HEIGHT)); 
   }

   private function mouseUpFinished():void
   {
       dragInProgress = false;
       this.stopDrag();

   }

请注意,函数现在在主类中定义,'setTimeout'使用函数名称传递引用。现在,在这些函数中使用'this'将正确引用主类。