Calling a Classes' Method From Another Class i

2019-09-01 05:44发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-09-01 06:19

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

查看更多
登录 后发表回答