Reputation: 57
As a beginner I've been told to avoid global variables cause names can collide specially as a project grows. But I'm also told coding is about efficiency and you should not do things twice. Avoiding global variables leaves me declaring the same variable in different functions which feels like the wrong thing to do. What is the way to go? Thank you, peace and love.
//GLOBAL SPACE - no variables here, wanna be a good boy
function one(){
var box = document.getElementsById('box');
//DO SOMETHING WITH BOX
}
function two(){
var box = document.getElementsById('box');
//DO SOMETHING ELSE WITH BOX
}
Upvotes: 4
Views: 58
Reputation: 10528
JavaScript relies heavily on Closures. The functions in the global namespace are closures too. Either use the OOP approach (about OOP encapsulation) or (as already noted in the comments) the Module pattern. The holy grail of programming is abstraction (unless you consider zeros and ones more elegant), and encapsulation by OOP is one of the major approaches. For instance:
var my_object = {
box: document.getElementsById('box'),
one: function() { }, // manipulate this.box
two: function() { }, // manipulate this.box
};
Upvotes: 1
Reputation: 21742
redeclare your funcitons to take an argument
function one(box){
//DO SOMETHING WITH BOX
}
That also has the advantage of moving the location of the box to just one place. Either a declaration or it's own function. Which again means that if you change how to locate the box element you won't have to change it in all methods that use it but only at one place.
Upvotes: 1
Reputation: 82267
It really depends on how one
and two
are being accessed. You could always close over the box variable like this though:
var one,two;
(function(){
var box = document.getElementById('box');
one = function(){
//use box
};
two = function(){
//use box
};
})()
Upvotes: 4