0
votes

I am very new in actionscript 3 I have a problem to convert "this" keyword from as2 to as3. please help me!

thanks !

My as2 code is:

var selected = MovieClip(null);
j = 1;
while (j++, j <= 11)
{
    var obj_1 = this["shape" + j];
    obj_1.highlight._visible = false;
    obj_1.onPress = function()
    {
        if (_root.selected)
        {
            _root.selected.highlight._visible = false;
        }
        // end if        
        this.highlight._visible = true;
        _root.selected = this;
        trace(this)
    };
}// end while

and my as3 code is:

var selecteD = MovieClip(null);

    var j:int = 1;

while (j < 11)
{
    j++;
    var obj_1:MovieClip = this['shape' + j];
    //trace(obj_1);
    obj_1.highlight.visible = false;
    obj_1.addEventListener(MouseEvent.CLICK, pressed);
    function pressed(event:MouseEvent):void
    {

        if (MovieClip(root).selecteD)
        {
            trace(MovieClip(root).selecteD);

            selecteD.highlight.visible = false;
        }

        MovieClip(root).selecteD = **this**;
        MovieClip(root).selecteD.highlight.visible = true;

    }
}

when i trace this the result come Object main timeline in as3 but in as2 it is the level0.shape11

how could i convert "this" for this project.

please help!

2

2 Answers

0
votes

in as2 this refers to the object you add the onPress function to, obj1. in as3 this refers to the class/object the function is defined in, in this case your main timeline. in as3 you can get the clicked object from the MouseEvent

while (j < 11)
{
    j++;
    var obj_1:MovieClip = this['shape' + j];
    //trace(obj_1);
    obj_1.highlight.visible = false;
    obj_1.addEventListener(MouseEvent.CLICK, pressed);
    function pressed(event:MouseEvent):void
    {


        if (MovieClip(root).selecteD)
        {
            trace(MovieClip(root).selecteD);

            selecteD.highlight.visible = false;
        }

        var clickedObject:MovieClip = event.currentTarget as MovieClip;
        MovieClip(root).selecteD = clickedObject;
        MovieClip(root).selecteD.highlight.visible = true;

    }
}
0
votes

The documentation words it well:

A reference to a method's containing object. When a script executes, the this keyword references the object that contains the script. Inside a method body, the this keyword references the class instance that contains the called method.

It's important to note that Function.call() and Function.apply() are still present in AS3, which can alter the expected value of this in some instances.