user1995781
user1995781

Reputation: 19463

Actionscript access global / class variable

Here is my code:

package
{
import flash.display.Sprite;

public class MyClass extends Sprite
{
    private var abc:String = "123";
    public function MyClass()
    {

    }

    public function myfunc():void
    {
        dispatch("456");
    }

    private function dispatch(abc:String):void
    {
        trace(abc);
    }
}
}

When call the myfunc() function the trace will return 456. How can I get it to access to the global variable?

Thank you.

Upvotes: 0

Views: 126

Answers (2)

taskinoor
taskinoor

Reputation: 46037

First of all, private var abc:String = "123"; is not global variable. It's a private member variable of the class. It's scope is the full class. When you add parameter in a member method with the same name, that parameter has the local scope in that method and that local parameter variable hides the class member of the same name.

private function dispatch(abc:String):void {
    // here abc has local scope and it hides the class member abc
}

You have two options to solve this:

  1. Simply use a different name for the parameter. For example, private function dispatch(ab:String):void. Now ab is local variable, abc is class member variable.
  2. If you must use the same name for parameter then use this.abc to access the class member.

Upvotes: 1

Ivan Chernykh
Ivan Chernykh

Reputation: 42186

Use this keyword:

private function dispatch(abc:String):void
    {
       trace( this.abc );
    }

Upvotes: 4

Related Questions