开发者

call function out of class

I have this piece of code that has a problem. so can you help me?

package Classes
{
    import mx.controls.Button;

    public class Pages
    {
        public function Pages(){

        }

        public function LoginPage():void{
            AddButton('cmdLogin', 'Login');
        }

        private function AddButton(id:String, label:String, x:int, y:int, width:int, height:int):void {
            if (id.length > 0 && label.length > 0) {
            var button:Button = new Button();
            button.id = id;
            button.label = label;
            button.x = x;
            button.y = y;开发者_开发问答
            button.width = width;
            button.height = height;
            Main.addChild(button);
            }
        }
    }
}

Main.mxml

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
                   xmlns:s="library://ns.adobe.com/flex/spark" 
                   xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="main()">
        <fx:Script>
            <![CDATA[
                import Classes.Pages;

                private function main():void {
                    Pages.LoginPage();    // <---- HERE IS AN ERROR
//Description   Resource    Path    Location    Type
1061: Call to a possibly undefined method LoginPage through a reference with static type Class. Main.mxml   /File Hosting/src   line 30 Flex Problem

                }

            ]]>
        </fx:Script>
    </s:Application>


The problem is you don't realize the difference between classes and instances of classes. I recommend you to read more about OOP from the basics. Because of even if you'll follow advices of @Lars Blåsjö, you'll have a problem in the line:

Main.addChild(button);

which refers to the class Main but not the instance. And the class Main hasn't (static) method addChild(). So it will be an other compiler error. But compiler errors are not the problem. You'll easily fix them. The problem is in OOP understanding and understanding of classes and instances interaction and OOP principles and, as a result, lack of architecture where all the code uses globals or statics or has high coupling.

So please read more about OOP and design patterns. It can change your future :)


If you want to call a method on a class, rather than create an instance of that class and call the method of that instance, you need to declare the function as static.

So you could do this:

public static function LoginPage():void{
   AddButton('cmdLogin', 'Login');
}

...

Pages.LoginPage();

... or you could make an instance of Pages, and call the method on that object, which can be considered the normal case:

var pages:Pages = new Pages();
pages.LoginPage();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜