Book Image

haXe 2 Beginner's Guide

5 (1)
Book Image

haXe 2 Beginner's Guide

5 (1)

Overview of this book

Table of Contents (21 chapters)
haxe 2
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – Writing an extern


Imagine that we are writing a User class in JavaScript:

function User()
{
   var name;
   var age;
}
User.prototype.outputInfo = function()
{
   var el = document.createElement("div");
   el.innerHTML = this.name+"("+ this.age+")";
   document.body.appendChild(el);
}

Now, if we want to use this class from our haXe application, then we have to write the corresponding extern class as follows:

extern class User
{
   public var name:String;
   public var age:Int;
   public function outputInfo():Void;
   public function new():Void;
}

There are several things that you should note:

  • You have to prefix your class declaration with the extern keyword

  • We do not write any code inside function declaration

  • Constructors should be declared returning Void

What just happened?

We have written an extern class, explaining to the compiler that the User class exists outside our code and can be used from it.

Using an extern

Now, we can use this class in our haXe code:

class Main
{   ...