One comprehensive definition of JavaScript closure

I read 10 of SO closing links, MDN links and other blog articles. They all seem to define closure in their own way. For example, from the MDN documentation:

function makeFunc() {
  var name = "Mozilla";
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

And here is their explanation of the closure:

Usually local variables inside a function exist only for the duration of the function. Once makeFunc () completes the execution, it is reasonable to expect that the name variable will no longer be available. Since the code still works as expected, this is obviously not the case.

, myFunc . - , : , . , . myFunc , displayName, "Mozilla", .

StackOverflow . Javascript?

: ? " ", , , , ? (), , myFunc, ?

+4
3

,

, . , , , .

:

var v1; // I'm accessible anywhere    
function a() {
    var v2;
    function b() { // I can access v2 and v1
        var v3;
        function c() {  // I can access v1, v2, v3
            var v4;
        }
        return c;
    }
    return b();
}
var f = a();

a, b, c , , window .


, . , -, , , factory .

+2

JS :

class Function : Object {
  bytes      bytecode;
  varframe   varsAndArgs;
}

class varframe{
  array<value>  values;
  ptr<varframe> parent;
}

, JS . null.

,

function makeFunc() {
  var name = "Mozilla";
  function displayName() {
    alert(name);
  }
  return displayName;
}

displayName (const/variable) Function, varframe :

varframe(displayName) 
  values[0] // empty array, no variables in it
  parent -> varframe(makeFunc) 
              values[1] // one variable "name" at index 0;
              parent = null    

, , varframes (a.k.a. callframes).

+1

, , OO JavaScript, . , JS-. " JavaScript " , JavaScript. Ninja :

"... , , , ​​ .

                                         -- "Chapter 5: Closing in on closures"

, JavaScript ( ) :

  • , ;
  • , ( JavaScript );
  • , "" .

JavaScript 2. 11 " " gibhub :

, , : .

0
source

All Articles