So I have a rather large object orientated javascript class, with about 120 functions (a lot of getters and setters). Some of these functions have variables that are basically constants.
What I’m wondering, is should I declare these variables in a global scope of the object, so every time the function is run it doesn’t have to re-declare the variable?
An example function is below. this.displayContacts is run several times (and will always run within the object), so in this case, there’s no point declaring the ‘codes’ object inside the function?
function orderObject() {
this.displayContacts = function() {
var codes = {'02':'02','03':'03','07':'07','08':'08'};
// do something with codes
};
}
So, would this be better, performance wise?
function orderObject() {
var codes = {'02':'02','03':'03','07':'07','08':'08'};
this.displayContacts = function() {
// do something with codes.
};
}
My other concern is that if I end up with a lot of global variables/objects inside the main orderObject, will that be MORE of a performance hit than simply re-declaring the variables each time?
absolutely.
CONSTANTis ‘static’ so to speak, in java-talk. If yourcodesare global to the class (and the rest of your application), you will save a lot of overhead this way — only define the object once. Note that you can have ‘static’ class-level methods as well, for those cases where the function doesn’t need to operate on variables specific to an instance of the class.Unless your app is really beefy, performance optimization probably wont make it noticeably faster. But that doesn’t mean that OO design is not worth-while — if you are going to use javascript in an object oriented way, its not too hard and never a bad idea to use good OO principals.