HaxeFoundation / HaxeFoundation/haxe
[js] Static field should be defined just after class definition
- Dominant language
- Haxe
- Stars
- 6.9k
- Forks
- 715
- Avg merge
- 2d 2h
- Merged PRs (30d)
- 11
Description
Using Haxe version 3.3.0.
In JavaScript, static fields should be defined just after the definition of the classes. Else, static fields from the Main class can instantiate classes that use undefined variables.
The following code gives bad result.
``` hxml
# Compile file
-js output.js
-main Main
```
``` Haxe
// Main.hx
package;
class Main
{
public static var rectangle:Rectangle = new Rectangle();
static public function main()
{
}
}
```
``` Haxe
// Rectangle.hx
package;
class Rectangle
{
public var leftUp:Point = new Point();
public var rightBottom:Point = new Point();
public function new()
{
}
}
```
``` Haxe
// Point.hx
package;
class Point
{
public static var DEFAULT_X(default, null):Float = 0;
public static var DEFAULT_Y(default, null):Float = 0;
private var x:Float;
private var y:Float;
public function new()
{
x = DEFAULT_X;
y = DEFAULT_Y;
trace('x = $x');
}
}
```
``` javascript
// output.js
// Generated by Haxe 3.3.0
(function () { "use strict";
var Rectangle = function() {
this.rightBottom = new Point();
this.leftUp = new Point();
};
var Main = function() { };
Main.main = function() {
};
var Point = function() {
this.x = Point.DEFAULT_X;
this.y = Point.DEFAULT_Y;
console.log("x = " + this.x);
};
Main.rectangle = new Rectangle(); //Here: Point.DEFAULT_X used but not defined
Point.DEFAULT_X = 0;
Point.DEFAULT_Y = 0;
Main.main();
})();
```
Output:
```
x = undefined
x = undefined
```
To work correctly, here is how the output JavaScript file should be:
``` javascript
// Generated by Haxe 3.3.0
(function () { "use strict";
var Rectangle = function() {
this.rightBottom = new Point();
this.leftUp = new Point();
};
var Main = function() { };
Main.main = function() {
};
var Point = function() {
this.x = Point.DEFAULT_X;
this.y = Point.DEFAULT_Y;
console.log("x = " + this.x);
};
Point.DEFAULT_X = 0; // Static fields defined just after the class definition
Point.DEFAULT_Y = 0;
Main.rectangle = new Rectangle();
Main.main();
})();
```
Output:
```
x = 0
x = 0
```
Contributor guide
Assessment
This issue has not been assessed yet.