I prefer to declare one Javascript file for my all website. I am trying to decrease the usage of global variables. My examples at the below, in both case each object has a myName field.
- I would like to know when they are initialized?
- And In terms of memory and efficiency which one is more effective?
- For variable a, is declaring a.myName the same as global “var myName = Rebecca” ?
var a = {
myName : 'Rebecca' ,
sayHello : function() {
console.log(this.myName);
}
};
var b = {
myName : function() {
return 'Rebecca';
},
sayHello : function() {
console.log(this.myName());
}
};
Thanks
I believe these will be initialized identically (i.e. when the code is reached). What’s different is what’s happening when they are initialized and where the load is placed when their data is actually required.
To me, it would depend a lot on what you were expecting to have in
myName. If it were just a string, I’d avoid the function and go with choice a. On the other hand, if there were a great deal of logic involved and that logic might not need to be invoked (for example, if it only gets executed when a user clicks on a button or the application reaches a certain state), I’d go with choice b. As I understand it, the function does consume memory and won’t get garbage collected (which is a minus), but it also won’t consume CPU resources until it’s actually needed (which can be a huge plus).I’m not sure I understand the question, but I’d say it’s not the same. If the only member of
aismyNamethen the two are equivalent (both are occupying the global namespace. But if you have multiple properties, the savings become obvious. From your examples, I think it’s clear you understand this, so again I may not understand the question.