/    Sign up×
Community /Pin to ProfileBookmark

Hey all,

I’ve been coding in JavaScript for a long while but lately I’m starting to notice how sloppy and unreusable much of my code is plus alot could generate global conflicts due to not understanding exactly how to avoid globals.

So I read a few articles and the first one suggested namespaces (this is familiar from C#)

[CODE]
var myNamespace = {
doSomething: function(){
return “doSomething”;
},
otherThing: function(){
return “otherThing”;
}
}
myNamespace.doSomething();
[/CODE]

While it seems clean it still doesn’t avoid the concept of using global. If anything it encourages it as everything you wrote all variables and all functions are now globally accessible via the namespace.

This led me to reading about anonymous function wrappers and then just returning an interface. So to try and put the idea in my head I made this code:

[CODE]
(function(){
var Interface = {
Run: function(func){
switch(func){
case 0: helloWorld(); break;
case 1: byeWorld(); break;
case 2: otherWorld(); break;
};
}
};
function helloWorld(){
$(“body”).append(“hello world”);
}
function byeWorld(){
$(“body”).append(“bye world”);
}
function otherWorld(){
$(“body”).append(“other world”);
}
return Interface;
}());
[/CODE]

Now this loaded error free, but obviously still doesn’t do anything. Even if I tried to call [B]Interface.Run(1);[/B] from another script. So I misinterpreted thinking that it returned only an interface to global it seemed if I didn’t assign a variable to my anonymous function only the code in it would be executed and nothing would be returned. Now this isn’t bad if say it was just a one time run script and good to go. But what if it was an active library that I wanted to call from multiple different scripts? So I finally got it to work by doing.

[CODE]var x = (function(){
var Interface = {
Run: function(func){
switch(func){
case 0: helloWorld(); break;
case 1: byeWorld(); break;
case 2: otherWorld(); break;
};
}
};
function helloWorld(){
$(“body”).append(“hello world”);
}
function byeWorld(){
$(“body”).append(“bye world”);
}
function otherWorld(){
$(“body”).append(“other world”);
}
return Interface;
}());
x.Run(2);
[/CODE]

Now this works to hide my functions that I don’t want externals to see, but I’m still left with a global x making it look very similar to a namespace, but it is just hiding any information from other scripts that is NOT available in the interface. Now this is good in the sense that I can now check to see if X exhists and then assign it if it does not avoiding any potential global conflicts. Also the interface is NOT dependant on the “class” that uses it having the same functionality so I can grow this class as needed and as long as the interface remains the same then ANY external can use this without changing or breaking its contents.

This still leaves me at the mercy of other programmers though (hoping they check to see if my global variable exhists before overwriting it.) Obviously I wouldn’t want to use the var X, but more something bland was an example of how easy it would be for the next script loaded after mine to assign a variable X and overwrite mine making any other scripts dependant on my global namespace crash and burn.

Is there a smarter way to do this that avoids globals, keeps modularity, and leaves you scratch free if other programmers are running around hacking with swords?
Thanks for your time. I am aware this may be a matter of opinion and I don’t mind that. I am interested in just learning the perspectives of some more experienced JavaScript poets than I.

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@Jeff_MottJan 23.2015 — Now this works to hide my functions that I don't want externals to see, but I'm still left with a global x making it look very similar to a namespace[/QUOTE]

When we say avoid globals, we mean that your library should introduce one -- and only one -- symbol into the global scope, and that one symbol is the entry point to your library. You'll need to name it uniquely enough that it's not likely to be overwritten. Ideally, follow a VendorNameProjectName convention (e.g., LesshardtoofindHelloWorld). Yes, other scripts could still overwrite your library, but that's not unique to you. They could also overwrite "Object" or "Date" or really anything. That's a fact of life in JavaScript. For you to write good code, all you need do is stay within your private sandbox and expose only one well named global symbol.
×

Success!

Help @Lesshardtoofind spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...