开发者

ActionScript 3 constructor scope question

out of curiosity I decided to experiment with the following in a Flex 4 project:

public class MyGroup extends Group
{       
    public function MyGroup()
    {
        super();
        var myLabel:Label = new Label();
        myLabel.id = "myLabel";
        myLabel.text = "My label!";
        this.addElement(myLabel);
    } etc.

This custom component does what I'd expect; it looks like a label control with text="My label!".

Question: is there any way to reference the myLabel label control (e.g. to change the text) elsewhere in the project?

At the moment the only way I can get to the inner label control is by calling 开发者_StackOverflow中文版something like myGroup.getElementAt(0).

I realize that it would make more sense to have the label be a class variable -- I'm just wondering how this code works.


You can make a public setter to change you text label:

public class MyGroup extends Group
{
    private var _label:Label=new Label();

    public function set label(value:String):void{
      _label.text=value;
    }

    public function MyGroup()
    {
        super();
        _label.id = "myLabel";
        label = "My label!";
        addElement(_label);
    }
.....
}

var myGroup:MyGroup=..
myGroup.label="Hello";

In your case since you are declaring your var myLabel inside a function, it 's scope will only apply inside this function


In ActionScript, variables are named handles that you can pull on to get objects and data. Variables have something called scope, which specifies in what parts of the code the handle is valid.

When you create a variable inside a function, its scope is that function. That is, that particular named handle is only usable inside that function.

In your code, you create a handle called myLabel, and put a Label in it--let's call it Label123. Next you put Label123 into the element list of MyGroup, which gives MyGroup a handle attached to Label123. Then the function ends, and the handle called myLabel is no longer usable. Label123 still exists, because MyGroup has a handle to it.

If you create myLabel as a private or protected class variable, that handle will be usable from any function inside MyGroup. If you create it as a public class variable, it will be usable anywhere inside MyGroup, and also anywhere in the code you have an instance of MyGroup. (And if you create it as an internal class variable, it will be usable anywhere inside the package MyGroup is in.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜