JavaScript Strict mode
The first contact with the Let keyword, there is a very very important concept is "JavaScript strict mode", such as the following code to run the error:
' Hello world. ' ; Console.log (hello);
The error message is as follows:
' Hello world. ' ; ^^ ^syntaxerror:blockconstclass) Not yet supported outside strict mode ...
The workaround is to add a "JavaScript strict mode" declaration to the file header:
' Use Strict ' 'Hello world. ' ; Console.log (hello);
For more detailed instructions on "JavaScript strict mode", please refer to Nanyi's blog
A detailed description of Javascript in strict mode
Let and VAR keywords are not assigned after the declaration of similarities and differences, the same performance
' Use Strict ' ;(function () { var vartest; Let Lettest; // output undefined // output undefined} ());
Use undeclared variables to behave differently:
(function () { // output undefined (note to comment out the following line to run) // Direct error: Referenceerror:lettest is not defined var'test var OK. ' ; ' test let OK. ' ;} ());
When declaring the same variable repeatedly, it behaves differently:
'Use Strict';(function () {varVartest ='test var OK.'; Let Lettest='test let OK.'; varVartest ='Vartest changed.'; Let Lettest='Lettest changed.';//Direct error: Syntaxerror:identifier ' Lettest ' has already been declaredConsole.log (vartest);//output vartest changed. (Note that you need to comment out the duplicate declaration of the Lettest variable above to run)Console.log (lettest);} ());
Variable action range, different performance
'Use Strict';(function () {varVartest ='test var OK.'; Let Lettest='test let OK.'; { varVartest ='Vartest changed.'; Let Lettest='Lettest changed.'; } console.log (Vartest); //output "vartest changed.", vartest variable declared in internal "{}" overrides the external Lettest declarationConsole.log (lettest);//output "Test let OK.", Lettest declared in internal "{}" and external lettest are not the same variable}());
Egret under:
Using the undefined let:
class Test { public name:string"Test"; Public run () { console.log (a);//The line error block-scoped variable ' a ' used before its declaration. Console.log (b); Let A; var b; }}
Duplicate define Let:
class Test { public name:string"Test"; Public Run () {let A; The line error cannot redeclare block-scoped variable ' a '. var b; Let A; var b; //The bank error Cannot redeclare block-scoped variable ' a '.
}}
Variable range:
classTest { PublicNamestring="Test"; PublicRun () {Let a=1; varb =2; {Let a=2; varb =2; } console.log (a); //1Console.log (b);//2 }}
The difference between let and Var defined variables in TS and JS