简体   繁体   中英

JavaScript: implement let-working with var

So I have a code that clone let-behavior. But I don't undestand how and why it is working. Can someone explain it?

(function() {
  var a = 2;
})()

let is scoped to the block it appears in.

var is scoped to the function it appears in.

By replacing a block with a function (which is immediately invoked) var is scoped to the same lines of code as let would be.

Where you can only use var variables but you want to ensure that a variable declaration is not going to overwrite another pre-existing variable of the same name, you can use an IIFE to scope that variable to the function. This in effect creates a "block", similar to the second example below.

var variables are scoped to functions:

 var a = 1; let b = 1; (function() { var a = 2; let b = 1; })(); console.log(a); //=> 1 (a is not overwritten because the second `var a` is function-scoped) console.log(b); //=> 1

let variables are scoped to blocks:

 let a = 1; var b = 1; { let a = 2; var b = 2; } console.log(a); //=> 1 (a is not overwritten as let is block-scoped) console.log(b); //=> 2 (b is overwritten as var is not block-scoped)

It's worth mentioning that you can redeclare a var variable, hence why it would be possible to overwrite an existing var variable of the same name. However, you cannot redeclare a let variable:

 var a = 1 // will not error as `var` does not prevent redeclaration var a = 2 let b = 1 { // will not error as `b` is not declared in this block let b = 2 } // will error as `b` is already declared in this scope let b = 3

You can read more about let and var in this question and its answers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM