Javascript: How to reference objects from other files?
Hi!
I was playing around in Microstudio and found out that it supports Javascript, a language I already am familiar with, so that sounds like an easy start.
But I am unable to determine what the load order is, or how to use imports, etc. I would like to define classes in another file and not end up with one big source file.
Any suggestions?
Source files in microStudio will indeed be loaded in a random order. In order to make it work, you will have to:
- Define your classes, in separate files as you wish, as global variables
- Only start creating object instances from your classes when or after init() is called ; the call to init is the signal that all your source files have been loaded.
Example:
File "myclass"
MyClass = class {
constructor(x) {
this.x = x ;
}
}
File "main"
init = function() {
obj = new MyClass(1234) ;
}
update = function() {
}
draw = function() {
screen.drawText(obj.x,0,0,50,"rgb(255,255,255)")
}
Ah ok.
So extending from classes from other files is currently not possible, clear!
Is there anything on the roadmap like an import or require mechanism?
I understand there is something to be improved here, I will definitely have to think about it (do you think being able to set the file loading order could completely solve the problem?).
This said, it would be currently possible to use classes and extended classes defined in separate files, using custom "import" functions, like this:
File "class1"
import_class1 = function() {
Class1 = class {
constructor(x) {
this.x = x ;
}
}
}
File "class2" - (Class2 extends Class1)
import_class2 = function() {
Class2 = class extends Class1 {
constructor(x) {
super(x) ;
}
}
}
File "main"
init = function() {
import_class1() ; // loading classes
import_class2() ; // in the correct order
obj = new Class2(1234) ;
}
draw = function() {
screen.drawText(obj.x,0,0,20,"rgb(255,255,255)") ;
}
That is a good way to work around the problem, I noticed that in microscript this issue does not really exist, probably due to your transpiler.
What would be helpful is to give priority to one file, like "init". So that you could define some global variables that are always loaded first. This way you could implement a require function yourself to register your classes. The rest could then be loaded in random order.
But thanks for providing an answer to my question, now I know that it is in random order I can work toward a solution :) Or just use your Microscript, which in the end will probably have a better experience!