- Home /
Putting extra classes into JS script a no no?
As I understand it, each JS script becomes a class with the same name as the script.
Occasionally, I've been adding a different class, which the script (or other scripts) may access, into a JS script in the same place as declaring the script variables:
Script "MyScript.js":
var foo : int; var bar : int;
class AnotherClass { var foo2 : int; var bar2 : int; function AnotherClass( f : int, b : int ) { foo2 = f; bar2 = b; } function Switch() { var tmp : int = foo2; foo2 = bar2; bar2 = tmp; } }
var another : AnotherClass;
function Start() { foo = 0; bar = 100; another = new AnotherClass( 3, 7 ); }
function Update() { foo++; if (foo==bar) { foo = 0; another.Switch(); } }
This works perfectly well, and I can make instances of AnotherClass from any script. But is this bad coding practice? Should I put AnotherClass into its own script? And is it different if I start coding in C# down the line?
No problem with this at all. Everything else will know about such classes, no problem. It's just a matter of tidyness, you may prefer to group such "little" classes in one file.
Answer by Eric5h5 · Feb 18, 2011 at 06:51 PM
No, it's not necessarily bad practice, and it's not any different in C#. If the class is really generic and not related to any specific script, I would be inclined to put it in its own script for the sake of organization and clarity.
Just out of interest are Javascript classes defined that way scoped within the hidden outer class?