Search code examples
flashactionscriptthistween

"this" is undefined


I am a java/php developer helping someone with actionscript. I don't understand why "this" is undefined in the below code. this is only a snippet of the code, but hopefully it's gives an idea of where i'm trying to reference "this". I'm trying to find out which movie the tween is moving so that i can load the next movie. Tweens are used to move the movies in and out of the screen.

var tween_move_1:Tween = new Tween(movie_0, "_x", Strong.easeOut, 1600, 150, 0.5, true);

tween_move_1.onMotionFinished = function() {
    stop();
    setTimeout(function () {
        trace(this);//when trace runs it shows undefined
        var tween_move_2:Tween = new Tween(movie_0, "_x", Strong.easeOut, 150, 1600, 0.5, true);
        tween_move_2.onMotionFinished = function() {
        var tween_move_1:Tween = new Tween(movie_1, "_x", Strong.easeOut, 1600, 150, 0.5, true);
        };
    }
    ,2000);//end of setTimeout
};//end of tween.onMotionFinished

UPDATE! Here is the working code after applying tips from the responses/answers:

var tween_move_in:Tween = new Tween(movie_0, "_x", Strong.easeOut, 1600, 150, 0.5, true);   
tween_move_in.onMotionFinished = function() {
    stop();
    var tweeny = this;//create reference to this so it can be used in setTimeout()
    setTimeout(function () {
         var movie = tweeny.obj;//use ref to get the movie affected by the tween
         var movieName:String = movie._name;
         var splitArray = movieName.split("_");
         var index = parseInt(splitArray[1]);
         var tween_move_out:Tween = new Tween(_root["movie_"+index], "_x", Strong.easeOut, 150, 1600, 0.5, true);
         tween_move_out.onMotionFinished = function() {
              var tween_move_in2:Tween = new Tween(_root["movie_"+(index+1)], "_x", Strong.easeOut, 1600, 150, 0.5, true);
         };
    }
    ,2000);//end of setTimeout
};//end of tween.onMotionFinished

Solution

  • If you trying to trace out tween_move_1, you can refer to it directly inside the setTimeout().