Calling a Classes' Method From Another Class in Flash

别来无恙 提交于 2020-01-25 08:24:25

问题


If I have a document class:

package {
    import flash.display.MovieClip;

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

        }            
        public function SomeRandomMethod():void {

        }
    }
}

How can I call SomeRandomMethod from here:

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

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

回答1:


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



来源:https://stackoverflow.com/questions/7302584/calling-a-classes-method-from-another-class-in-flash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!