当前位置:网站首页>ES6 learning -- let

ES6 learning -- let

2022-06-25 23:02:00 Climbing procedural ape

characteristic

(1) Variable declarations cannot be repeated

(2) Variable has block level scope

(3) The variable does not exist , That is, use first and then declare

(4)  Does not affect the chain of action

Characteristic cases :

(1) Variable declarations cannot be repeated , Repeat and make mistakes , Stop script  Uncaught SyntaxError: Identifier 'b' has already been declared

            //  Variable declarations cannot be repeated 
            var a = 0
            var a = 10
            console.log(a)
            //  Without the following , Here you can output , When you add the following, the output is b has already been declared, even 10 Will not output 
            let b = 10;
            let b = 11;
            console.log(b)
//Uncaught SyntaxError: Identifier 'b' has already been declared

(2) Block level scope

			//  Block level scope 
            {
                var testBlockVar = ' Test block ';
                let testBlockLet = ' Test block ';
            }
			console.log(testBlockVar)
			console.log(testBlockLet)

Echo as follows , The previous one here is executable ,let When there is a conflict, it will not be implemented
 Insert picture description here

 (3) Variable Promotion   --  Use directly before declaring variables

            console.log(testUpLet)
            console.log(testUpVar)
            var testUpVar = ' Test variable promotion ';
            let testUpLet = ' Test variable promotion '

notes :let Can be used before declaration , The value is undefined,let Will report a mistake , And stop the program directly where the error is reported

 (4) Does not affect the chain of action   --  Will look up let The variable of

            {
                let testGlobal = ' Outside shangsilicon Valley ';
                let testGlobal1 = ' Silicon Valley 1'

                function f() {
                    let testGlobal = ' In Silicon Valley ';
                    console.log(testGlobal)
                    console.log(testGlobal1)
                }

                f();
            }

Will look up for variables , If you internally define the same variable , Then use its own sibling variables

  Typical problems

(1)let Modify block scope

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<style>
			.item {
				height: 50px;
				width: 50px;
				border: 1px solid black;
				display: inline-block;
			}
		</style>
	</head>
	<body>
		<div class="pageheader"> Click to switch colors </div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<div class="item"></div>
		<script>
            let items = document.getElementsByClassName('item')
            for (var i = 0; i < items.length; i++) {
                items[i].onclick = function () {
                    // this.style.backgroundColor = 'pink'; //  Write it correctly 
                    items[i].style.backgroundColor = 'pink' //  Wrong writing , Will throw out  Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
                }
            }
            //  The cause of the error is analyzed as follows , because function stay click Only when it's time to execute , here i The value of is global , Has become 3, So we couldn't find items[3], Modified into let when , Clicking time , I will find my own piece , Each of the following blocks ,function There is no , Then find the top in the block ,let i = 0/1/2/3
            {
                var i = 0;
                items[0].onclick = function () {
                    // this.style.backgroundColor = 'pink'; //  Write it correctly 
                    items[i].style.backgroundColor = 'pink' //  Wrong writing , Will throw out  Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
                }
            }
            {
                var i = 1;
                items[1].onclick = function () {
                    // this.style.backgroundColor = 'pink'; //  Write it correctly 
                    items[i].style.backgroundColor = 'pink' //  Wrong writing , Will throw out  Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
                }
            }
            {
                var i = 2;
                items[2].onclick = function () {
                    // this.style.backgroundColor = 'pink'; //  Write it correctly 
                    items[i].style.backgroundColor = 'pink' //  Wrong writing , Will throw out  Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
                }
            }
            {
                var i = 3;
                items[3].onclick = function () {
                    // this.style.backgroundColor = 'pink'; //  Write it correctly 
                    items[i].style.backgroundColor = 'pink' //  Wrong writing , Will throw out  Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
                }
            }


		</script>
	</body>
</html>

(2) The closure of the above case is modified

notes : It can be seen that immediately executing the function will form its own closed space , It will not be affected by other external variables , In fact, if there is another one return It is a standard closure .

		<script>
            let items = document.getElementsByClassName('item')
            for (var i = 0; i < items.length; i++) {
                (function (i) {
                    items[i].onclick = function () {
                        items[i].style.backgroundColor = 'pink';
                    }
                })(i)
            }

		</script>

The closure function is disassembled , Similar to the following picture , It can be seen that , Parameter passing has its own scope inside the function ,i No longer in use for Block level domain of the loop .

		<script>
            let items = document.getElementsByClassName('item')

            function setOnclick(i) {
                items[i].onclick = function () {
                    items[i].style.backgroundColor = 'pink';
                }
            }

            for (var i = 0; i < items.length; i++) {
                setOnclick(i)
            }

		</script>

(3) If the closure does not pass parameters , Use global parameters var Well

            let items = document.getElementsByClassName('item')
			var i = 0;

            function setOnclick() {
                items[i].onclick = function () {
                    console.log(i)
                    items[i].style.backgroundColor = 'pink';
                }
            }

            for (var i = 0; i < items.length; i++) {
                setOnclick()
            }
            console.log(i)

Obviously the , It's the same as up here , Every time for The cycle has put i The value of is added to 4, When you click next setOnclick There is no reference , Use global parameters i = 4

 

Similar cases are as follows :

// situation 1
// The outer function of a closure function has no initial value 
var i = 0;  // Global variables 

function outerFn(){
  function innnerFn(){
       i++;
       console.log(i);
  }
  return innnerFn;
}

var inner1 = outerFn(); // The outer function of the closure function also has no initial value , Global variables used 
var inner2 = outerFn(); 
// Two functions share the same global variable 
inner1();   //1
inner2();   //2
inner1();   //3
inner2();   //4

// situation 2
// The outer function of a closure function has an initial value 
function outerFn(){
var i = 0;
  function innnerFn(){
      i++;
      console.log(i);
  }
  return innnerFn;
}
var inner1 = outerFn();
var inner2 = outerFn();
inner1();   //1
inner2();   //1
inner1();   //2
inner2();   //2

(4) The ultimate question   --  Taxi problem

I don't understand where this problem is prone to error , Subsequent complement

            let car = (function () {
                let start = 12
                let total = 0
                return {
                    price(n) {
                        if (n <= 3) {
                            total = start;
                        } else {
                            total = start + (n - 3) * 5
                        }
                        return total
                    },
                    jam(flag) {
                        return flag ? total + 10 : total;
                    }
                }
            })()
            console.log(car.price(3))
            console.log(car.jam(true))
            console.log(car.jam(false))

Reference material : Silicon Valley Web front end ES6 course , cover ES6-ES11

                     Immediate execution function

 

原网站

版权声明
本文为[Climbing procedural ape]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251913429819.html