Declaring the variable outside the function makes the function use the same object every time.
An example (with an integer instead of an object, for simplicity's sake):
var c = {
theMethod: function () {
var m1 = 0;
return function (theParameter) {
m1++;
console.log( m1 );
}
}()
};
c.theMethod(); c.theMethod(); // output: 1 2
var d = {
theMethod: function () {
return function (theParameter) {
var m1 = 0;
m1++;
console.log( m1 );
}
}()
};
d.theMethod(); d.theMethod(); // output: 1 1
The self-invoking function works like this:
var c = {
theMethod: function () {
var m1 = 0;
return function (theParameter) {
m1++;
console.log( m1 );
}
}()
};
When the object c
is created, the self-invoking function invokes itself and theMethod
now equals the return value of that function. In this case the return value is another function.
c.theMethod = function( theParameter ) {
m1++;
console.log( m1 );
};
The variable m1
is available to the function because it was in scope when the function was defined.
From now on when you call c.theMethod()
you are always executing the inner function that was returned from the self-invoking function, which itself executed only once at the time the object was declared.
The self-invoking function works just like any function. Consider:
var c = {
theMethod: parseInt( someVariable, 10 )
};
You don't expect parseInt()
to execute every time you use the c.theMethod
variable. Replace parseInt
with an anonymous function as in the original and it's exactly the same thing.
theMethod
declaration. – Anthodium(function () { ... })()
. This is a convention that helps to flag up to anyone reading the code that you're going to immediately call the function with that second set of empty parentheses()
. Otherwise when someone readstheMethod: function () { ...
they're likely to assume that the function they're now reading is going to be the thing that runs whentheMethod
is called. – Harelip