JavaScript close versus local

I have a main Javascript file that is enclosed in an immediate closure (so as not to pollute the "global":

(function () {
"use strict";
   var closureVariable = [];
...
}());

I made a simple bone coding error when deleting a variable from the function header, so that my code had a comma instead of a comma:

function fred () {
    var i,

    closureVariable = [1,2,3,4];
    confused();
}
function confused () {
    console.log(closureVariable);     // Prints '[]'
}

Of course, the missing semicolon in the string "var i" was a problem. However, the behavior that I thought was about to happen is that my locally-defined variable "closVariable" should obscure the definition of a higher-level region, and the value of my locally-defined variable should be accessible to the functions below in the scope chain (that is, the "confused" function should have printed "[1,2,3,4]";

Javascript ?

+3
3

, , . , . , Javascript. , Javascript . , confused fred, fred. , fred confused, .

+3
var i,

    closureVariable = [1,2,3,4];

, fred , .

, fred, .

, , "closureVariable" .

+3

When you redefined closVariable, omitting the semicolon, it was redefined only in the context of the fred function. The confused function exists in the context of your closure, so it still sees the original closure. If you had a confusing function defined inside the fred function, it saw a new Variable closure and printed [1,2,3,4]

(function () {
  "use strict";
  var closureVariable = [];
  function fred () {
   var i,

   closureVariable = [1,2,3,4];

   function confused () {
      console.log(closureVariable);     
   }

   confused();  // print [1,2,3,4]
  }
 })();

Or if you want to cause confusion from abroad fred ()

(function () {
  "use strict";
  var closureVariable = [];
  var confused;

  function fred () {
   var i,

   closureVariable = [1,2,3,4];

   confused = function () {
      console.log(closureVariable);     
   }  
  }

  confused();  // print [1,2,3,4]
 })();
+1
source

All Articles