开发者

AS3 - References to argument, is that bad?

I read a question on stackoverflow (couldn't find it now) about how varia开发者_如何学JAVAbles in a method can be only accessed in that method, but the code still works with the answer being an analogy of a hotel room. In AS3, I believe everything that's not primitive gets passed as a reference. So, the following code would be the same as that question and isn't guaranteed to work?

public class Testy {
    private var foo:Array;

    public function Testy(input:Array) {
        // Allow the whole class to access it
        foo = input;
    }

    public function traceFoo(){
        trace(foo);
    }

}

Now, foo would be a reference to the input argument in the class' constructor. Is this safe code/good practice? Thanks!


Yes this is safe/good code practice as long as you don't want to manipulate the original Array. If you want to manipulate the original array, allow public access to the array by making it a public var or using a public getter/setter.


What you've described is a property, and is inline with encapsulation of object oriented programming.

This would expose a getter and setter:


package
{
    import flash.display.Sprite;

    public class Testy extends Sprite
    {
        private var _foo:Array;

        public function get foo():Array
        {
            return _foo;
        }

        public function set foo(value:Array):void
        {
            _foo = value;
        }

        public function Testy()
        {
            super();
        }

    }
}


Also it's better to return _foo.concat() in getter not to break encapsulation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜