简体   繁体   中英

Transforming JavaScript with let to var

I want write a program to remove all declaration of let in the javascript programs automatically . For statements like

function a(){
    "use strict"
  var a=1,b=1;
  if(true){
    let a=2;
    var b=2;
    var c=a+b;
    let d=a+b;
  } 
  alert(a);
  alert(b);
  alert(c);
  alert(d);

}
a();

I am thinking to use immediate functions to remove the let

function a(){
        "use strict"
      var a=1,b=1;
      if(true){
        (function(){
        let a=2;
        var b=2;
        var c=a+b;
        let d=a+b;
        })()
      } 
      alert(a);
      alert(b);
      alert(c);
      alert(d);

    }
    a();

maybe the scope of let is correct, but the scope of var will become incorrect.

Any suggestion on this?

I would suggest you to declare your variable before your Immediately-invoked function expression, like so:

function a(){
  "use strict"
  var a=1, b=1, c;
  if(true){
    (function(){
      let a=2;
      b=2;
      c=a+b;
      let d=a+b;
    })();
  }
  alert(a);
  alert(b);
  alert(c);
  alert(d);
}
a();

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