Many functions in my code use this structure:
options = {"param1": "yes", "param2" : "no"}
In JS I do not have to “define” this structure since it is a dynamic language.
But when I know the structure has a fixed set of fields, is it a best practice to declare it in some centralized way, just for clearness? The same goes for usage in local data members in a class. Is it a best practice to init all of them in a ctor or some other centralized way (for clearness)?
I know I could do that in comment but coming from a static language I want to know what is the javascript style.
(I’m hoping you normally have a
varon the front of that. 🙂 Without one, you’re falling prey to The Horror Of Implicit Globals.)There’s no real convention other than being clear. For me, “being clear” means a couple of things:
Put all
varstatements at the beginning of the scope, because that’s where they really are anyway.If something has a significant structure that won’t be changing much, assign it with an object literal (as you have) as early as reasonable.
…but “being clear” means different things to different people.
Yes, initialize all instance-specific properties in the constructor. Properties that the object may not need its own copy of can reside on the prototype:
There, an object created via
new Foo("x")will get its own propertybarwith the value"x", it’s own propertybazwith the value[], and an inherited propertydatumwith the value42. Putting those initializations in the constructor and on the prototype right next to it aid clarity.