Question

I am new to Haxe and probably this is a pretty basic question, which I can't really find an answer.

I see three ways to call main class:

1) use main()

//Entry point
public static main():void{
   //do something...
}

2) use constructor new()

//Constructor
public function new(){
   // init
}

3) use both main() and new()

static function main()
{
    Lib.window.onload = function(e) new Main();
}

public function new()
{
   //init
}

Is there a guideline or best practice to which one to use?

Thanks

Was it helpful?

Solution

Addressing all 3:

  1. static function main() {} is the correct entry point. No matter which target, Haxe always begins execution at main().
  2. The new() constructor isn't called automatically, if you want your main app to execute as an object rather than from a static function, you have to explicitly create the object: static function main() { new Main(); }
  3. Some people prefer to keep their code in an object, rather than in static functions, which is where your 3rd example comes from. I usually do, and that's what you show in your 3rd example.

A few extra points:

  • The steps things are executed is explained here, basic summary:
    • All types/classes are registered
    • Boot.__init() runs platform specific initializations
    • Classes which have static function __init__() initialization methods are initialized
    • Static variables are intiailzed
    • Your main() function is executed
  • If you compile a class without a -main Main argument, but with the class path/name as an argument (eg haxe my.pack.MyClass) and with no public static function main(), the class is compiled, but it is not run automatically. This can be useful if you are creating a library or something similar - your class is there, but it needs to be called explicitly by some other Javascript etc.
  • In Javascript, the Haxe code starts running as soon as it is loaded, possibly before the DOM is ready. That is why it is a good idea to do:

    static function main() {
      js.Lib.window.onload = function(e) { runMyApp(); }
    }
    

    As you did in your example, this is a good idea if you want your code to run after the DOM is ready. Whether on load you call another static function, or instantiate a new MyApp() and run your app from there, that is up to you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top