[ANSWERED] Class Definitions in Javascript
-
I am needing to create an array of objects within my Javascript Actor and am having difficulties in creating the necessary class definition
When I do the following:
class Test{}
function main()
{return 0;}I get a compiler error saying that "Test has already been declared". However, if I do the following:
function main() {
class Test{}
return 0;}
(putting the class definition within the body of the main function) then it works just fine.
I have not found any documentation that specifies that class definitions have to be within a function. Eventually I will need to develop different class structures and would want to put these definitions in an external .JS file
Any thoughts/suggestions? -
Using namespaces for your Classes should allow you to create the modular structure you are after.
Try defining your Class like:var MyApp = MyApp || {}; MyApp.MyClass = class { constructor(param1, param2) { this.param1 = param1; this.param2 = param2; } method1() { this.param1 = this.param1 + this.param1; } method2() { this.param2 = this.param2 + this.param2; } }
Then create an instance in main() like:
const myInstance = new MyApp.MyClass(3, 5);
This should allow you to name each class uniquely and include them from external files.