Scope. Closure.

Scope types

  • Global
  • Local
var a = 123; // global variable



var func = function(){
  var b = 123; // local variable
}
var k = 4;


var outer = function(){
  console.log(k);
  var k = 8;
  console.log(k);
  
  var inner = function(){
    console.log(k);
    var k = 12;
    console.log(k);
  }

  inner();
  console.log(k);

}

Scope chains

Closure.

Lexical environment

In JavaScript, all local variables and functions are properties of the special internal object, called LexicalEnvironment.

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created. 

Using closure

// какое значение выведет console.log()?

var first = function(){
  var index = 5;
  return function(){
    return index;
  }
}


var second = function(){
  var index = 15;
  console.log( first()() );
}

second();
// реализация вывода значений счетчика


var counter = 0;

function add() {
    counter += 1;
}

add();


// какая основная проблема текущей реализации?
// выход - использование замыканий


var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();

Made with Slides.com