I have a .js file where I am initialising two parameters which are used
in a seperate function :
var submyvar1;
var submyvar2;
function init(myvar1 , myvar2){
submyvar1= myvar1;
submyvar2= myvar2;
}
function (){
//subvar1 & subvar 2 used here
}
Is declaring global variables like this a bad practice ?
If so, what is the alternative, wrap the entire .js file in an object ?
Answer
At least it's not a good practice, you could use an immediated invoked function expression:
(function() {
var x;
var y;
window.init = function(xValue, yValue) {
x = xValue;
y = yValue;
}
window.doWhateverYouWant = function() {
console.log(x + y);
}
}());
You could use this pattern unless you need access your global variable outside this .js file, when an cross-accessing between .js files or elements are required, global variable is a simple solution (although you could use AMD or sth else instead).
No comments:
Post a Comment