开发者

Calling a Classes' Method From Another Class in Flash

If I have a document class:

package {
    import flash.display.MovieClip;

    public class Main extends MovieClip {
        public function Main() {

        }            
        public function SomeRandomMethod():void {

        }
    }
}
开发者_Go百科

How can I call SomeRandomMethod from here:

package {
    public class AnotherClass {
        public function AnotherClass() {

        }            
        public function AnotherRandomMethod():void {
            /* I need to use SomeRandomMethod here */
        }
    }
}


There are a few ways to achieve this. One way would be to pass a reference of the document class to the constructor of the other class:

package {
    public class AnotherClass {
        private var _doc:Main
        public function AnotherClass(doc:Main) {
            _doc = doc;        
        }            
        public function AnotherRandomMethod():void {
            _doc.SomeRandomMethod();
        }
    }
}

or to the function itself

package {
    public class AnotherClass {
        public function AnotherClass() {

        }            
        public function AnotherRandomMethod(doc:Main):void {
            doc.SomeRandomMethod();
        }
    }
}

You could also use a singleton design pattern by declaring a global static variable and assigning the document class to it. Although singletons are regarded as an anti-pattern. For example:

package {

        import flash.display.MovieClip;

        public class Main extends MovieClip {

            public static var instance:Main;

            public function Main() {
                instance = this;
            }            
            public function SomeRandomMethod():void {

            }
        }
}

then

package {
    public class AnotherClass {
        public function AnotherClass() {

        }            
        public function AnotherRandomMethod():void {
            Main.instance.AnotherRandomMethod();
        }
    }
}

Another way would be to make use of the Service Locator pattern (although some view it as an anti-pattern too). http://gameprogrammingpatterns.com/service-locator.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜