Позволяет ли заменить анонимные замыкания на наличие частных переменных? - PullRequest
2 голосов
/ 12 апреля 2019

Если вы хотите иметь какие-то частные переменные в JavaScript, вы можете поместить код в анонимное закрытие, верно? Теперь, с тех пор как let был включен, этот конкретный вариант использования замыкания исчез? Или это все еще актуально?

Пример на верхнем уровне:

// global variable a
var a = 6;

// using let
{
  // new variable a that only lives inside this block
  let a = 5;
  console.log(a); // => 5
}

console.log(a); // => 6

// using a closure
(function() {
  // again a new variable a that only lives in this closure
  var a = 3;
  console.log(a); // => 3
})();

console.log(a); // => 6

1 Ответ

2 голосов
/ 12 апреля 2019

В Javascript есть нечто, называемое Подъем , которое «поднимает» указанную выше переменную еще до инициализации.

// global variable a
var a = 6;

// using let
{
  // new variable a that only lives inside this block
  let a = 5;
  console.log(a); // => 5
}

console.log(a); // => 6

// using a closure
(function() {
  // again a new variable a that only lives in this closure
  var a = 3;
  console.log(a); // => 3
})();

console.log(a); // => 6

Таким образом, этот код изменяется на:

// The global variable 'a' is hoisted on the top of current scope which is Window as of now
var a;

// Initialization takes place as usual
a = 6;


// This is a block
{

  // This local variable 'a' is hoisted on the top of the current scope which is the 'block'
  let a;

  a = 5;
  console.log(a); // => 5
}

console.log(a); // => 6

// Using an IIFE
(function() {

  // This local variable 'a' is hoisted on the top of the current scope which is the block of IIFE
  var a;

  a = 3;
  console.log(a); // => 3
})();

console.log(a); // => 6

До ES6 мы использовали IIFE для создания переменных, которые не будут загрязнять глобальную область, но после ES6 мы обычно используем let и const, потому что они предоставляют block-scope .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...