I have the following code that wont run (I am trying to have 0 global variables).
function() {
var createworker = function() {
//private implemenation
var count = 0;
var task1 = function() {
count += 1;
console.log("task1 " + count);
};
var task2 = function() {
count += 1;
console.log("task2 " + count);
};
return {
// these are the aliases or the public api
// revealing module pattern mode
job1: task1,
job2: task2
};
};
var result = 2 + 2;
var worker = createworker();
worker.job1();
worker.job2();
worker.job2();
worker.job2();
worker.job2();
}();
JavaScript doesn't like that for some reason. But the following example or just wrapping the anonymous function in () allows its it call itself. What is going on here and why is this the case?
(function() {
var createworker = function() {
//private implemenation
var count = 0;
var task1 = function() {
count += 1;
console.log("task1 " + count);
};
var task2 = function() {
count += 1;
console.log("task2 " + count);
};
return {
// these are the aliases or the public api
// revealing module pattern mode
job1: task1,
job2: task2
};
};
var result = 2 + 2;
var worker = createworker();
worker.job1();
worker.job2();
worker.job2();
worker.job2();
worker.job2();
}());
Wrapping it in parenthesis is how you make it an expression. The result of the expression is the last argument, and since there is only one argument in there (the function) that is the value of the expression.
Once evaluated, the value of the expression (the function) is then called using the following set of parenthesis.
That is why it is wrapped in parenthesis, to create the actual expression.