In order to reduce interferences between several scripts, I know it's highly recommended to encapsulate the Javascript code. But how would you do it? Which would you consider a better script between the following?:
(function(limit) {
var total = 0,
a = 0,
b = 1,
abSum = 1;
do {
a = b;
b = abSum;
abSum = a + b;
if (abSum % 2 == 0) total += abSum;
} while (abSum <= limit)
console.log('euler2. Total: ' + total);
})(4000000);
I could even exchange the way I use variables so that Function 1 could use local variables as such, and Function 2 would use function properties, and it would also work.
Which way to use better? Which way to use variables?
Neither way for this particular problem. Furthermore, I've used many different ways, depending on the situation. The first question is, do you need to maintain state?
If not, then a simple function would suffice.
If you do, then there are several options available:
Things have turned even more complicated with your reply, because I don't know the right path for each case.
And why do you consider the examples I mentioned not good? The ones you posted are not encapsulated. They don't use any namespace. They all might crash with another script with a variable called Point.
And why do you consider the examples I mentioned not good? The ones you posted are not encapsulated. They don't use any namespace. They all might crash with another script with a variable called Point.
using no global variables is one goal of good code design, not the only one, nor even the most important.
providing easy code re-use using plain-jane methoding that a wide variety of programmers can read is more beneficial overall than a perfect stealth attack.
performance is another factor; each closure and anon function add additional call overhead, deeper lexical stack depth, and one more activation object for the host environment to manage. the closer your code is to global, the faster it runs.
it's also not apparent how i would find the functionality you posted from an external script. if i need to make 38 calculations, how simply and intuitively can i do so with your 2nd code?
in short, you have to balance a variety of factors based on your problem.
at the end of the day there is no perfect demo code, only good and bad solutions to real problem.
Bookmarks