Are following snippets exactly equal? If no what is the deference?
var x = (function() {
... //a
return function(){
... //b
};
})();
vs.
var x;
{
... //a
x = function(){
... //b
};
}
Are following snippets exactly equal? If no what is the deference?
var x = (function() {
... //a
return function(){
... //b
};
})();
vs.
var x;
{
... //a
x = function(){
... //b
};
}
There is a major difference: In JavaScript, blocks don't induce a new variable scope. Therefore, you can't define private variables in the // a
code block. Compare
var x = (function() {
var v = 42;
return function(){
return v;
};
})();
// v; would yield ReferenceError: v is not defined, so you need to call x
and
var x;
{
var v = 42;
x = function(){
return v;
};
}
// v is 42 here, that's not what's intended.
One major difference is that at the time of executing ...//a
, x doesn't exist. Now in your case, in both cases it is undefined
but generally speaking it's possible to access x variable during ...//a
while in the first case it's not.
Otherwise in your circumstances it's pretty same. After all in your case the code is basically refactored into a separate function just like in any other language.