Javascript Class
Does anyone have a working example of classes in multiple files, running in microStudio in Javascript language. I am not managing to correctly reference classes defined in other files from Main
.
I got this error:
Game is not defined, in the file "main" in line 2
and I have the "game" file already defined:
class Game {
constructor(){
this.tiles = [];
...
}
}
this.gameManager = function() {
class GameObject {
constructor(id, x1, y1, w1, h1) {
this.id = id;
this.x = x1; // Object x position
this.y = y1; // Object y position
this.z = 0; // Object z position, to be used to sort the depth
this.width = w1; // Object width
this.height = h1; // Object height
this.name = "test"; // The string name of the object
this.instances = []; // Hold instances of this object for grouping
}
// Add an instance of this object (called in gameManager.instanceCreate())
instanceCreate(x, y) {
return (this.instances.push(new GameObject(x, y, this.width, this.height)));
}
// Update the game object
update() {
}
}
class GameManager {
constructor() {
this.objects = []; // Hold a list of game objects
}
// Add an object to the object list
objectAdd() {
var id = this.objects.length;
this.objects.push(new GameObject(id, 0, 0, 0, 0));
return (this.objects[id]);
}
// Add an instance of a created object with the ID of id
instanceCreate(id, x, y) {
let i = this.objects[id].instanceCreate(x, y);
return (i);
}
}
return new GameManager();
};
You can use this example, sorry for the weird pieces of the blue in pieces, just copy of the the code. I hope this is good. :)
When programming in JavaScript, make sure classes and functions are defined in the global scope using assignments.
// not "function foo() {"
foo = function() {
// ...
}
// not "class Game {"
Game = class {
// ...
}