ECMAScript 6-11 notes one

One, Let declare variables

1. Declare the characteristics of variables

 let a;
 let b,c,d;

(1) Variables cannot be declared repeatedly

(2) Block-level scope, global, function, evel

For example, variables declared with let at the block-level scope cannot be accessed globally.

(3) There is no variable promotion

Using the var keyword to declare a variable can be promoted. The declared variable is equivalent to being declared at the beginning, and will not appear until after the assignment.


console.log(a);//undefined
  var a="lili";
  console.log(a);//lili

Let declared variables are not promoted, and an error will be reported

 console.log(a);
  let a="lili";
  console.log(a);//lili

(4) Does not affect the scope chain

The variable a and the function are in a block-level scope, and the calling function can access a.

 {
    
    
    let a="lili";
    function fun(){
    
    
         console.log(a);
     } 
     fun();
 }

2. Examples

Click the div to change the color of the div:

  <script>
   window.onload=function(){
    
    
       //获取div元素对象
 let item=document.getElementsByClassName("item");
      for(var i=0;i<item.length;i++){
    
    
          item[i].onclick=function(){
    
    
             this.style.background="yellow";
          }
      }
    }
    </script>

When using var to define a variable, an item[i].style.background="yellow";error will be reported if you use it, because the current i is 3, which is out of range. So you need to use this to represent this object every time you click on the element

 <script>
   window.onload=function(){
    
    
       //获取div元素对象
 let item=document.getElementsByClassName("item");
      for(let i=0;i<item.length;i++){
    
    
          item[i].onclick=function(){
    
    
             this.style.background="yellow";
          }
      }
    }
    </script>

When using let to declare the i variable, item[i].style.background="yellow";either this.style.background="yellow";can be used.

Two, const declaration constant

A constant is an amount that cannot be modified.

const NAME="孙悟空";

1. Be sure to assign an initial value.
2. Use uppercase as much as possible for general constants.
3. The value of the constant cannot be modified.
4. The constants defined in the block-level scope cannot be accessed globally.
5. Modifications to the elements of arrays and objects are not counted as constant modifications, and no error will be reported.

const NAME=["孙悟空","猪八戒"];
NAME.push("沙和尚");
console.log(NAME);
//数组的地址未变

3. ES6 Destructuring Assignment
ES6 allows extracting values ​​from arrays and objects according to a certain pattern, and assigning values ​​to variables, which is called destructuring assignment.

1. Deconstruction of the array

const F3=["孙悟空","猪八戒","沙和尚"];
//定义一个变量
let[sun,zhu,sha]=F3;
console.log(sun);//孙悟空

2. Deconstruction of the object

const sun={
    
    
      name:"孙悟空";
      age:18;
      sayName:function(){
    
    
      console.log(this.name);
}
};
let{
    
    name,age,sayName}=sun;
console.log(name);
sayName();//可以直接调用

Three, template string

1. Statement

ES6 introduces a new way of declaring strings, backticks ``

let str=`我是字符串哦`
console.log(str,typeof str);

2. Line breaks can appear directly in the content

//使用单引号直接换行会报错,需要进行拼串
let str='<ul>'+
         '<li>aa</li>'+
         '<li>bb</li>'+
         '</ul>';

Use template strings to wrap lines directly


let str=`<ul>
    <li>aa</li>
    <li>bb</li>
    </ul>`;

3. Variable splicing

Syntax: Variable 2= ${变量1} xxx;

let lovest="孙悟空";
let out=`${
      
      lovest}是最厉害的`;
console.log(out);//孙悟空是最厉害的

Fourth, simplify object writing

ES6 allows you to write variables and functions directly inside the curly braces as properties and methods of the object.

let name='孙悟空';
let sayHello=function(){
    
    
  console.log("hello");
};
const per={
    
    
 name,
 sayHello,
 change(){
    
    
     console.log("方法可以简化写");
 }
 /*
 change function(){
     console.log("方法可以简化写");
 }
*/
}

Five. Arrow function

1. ES6 allows the use of arrows (=>) to define functions

//之前声明一个函数
let fn=function(){
    
    
}
//使用箭头声明函数
let fn =(a,b)=>{
    
    
  return a+b;
}
//调用函数
fu(1,2);

2. Arrow function declaration features

(1) this is static, this always points to the value of this object under the scope of the function declaration.

//普通函数
function getName(){
    
    
  console.log(this.name);
}
//箭头函数
let getName2=()=>{
    
    
  console.log(this.name);
}
//设置window对象的name属性
window.name="李李";
const per={
    
    
  name:"lili";
}
//直接调用,直接调用全局的name
getName();//李李
getName2();//李李

//call方法调用
getName.call(per);//lili
getName2.call(per);//李李

2. Cannot instantiate the object as a constructor
3. Cannot use the arguments variable
4. Shorthand for arrow function
(1) Omit the parentheses, when there is only one new parameter

let add= n =>{
    
    
 return n;
}
console.log(add(9));

(2) Omit the curly braces. When there is only one statement in the code body, return must also be omitted at this time, and the execution result of the statement is the return value of the function.

let pow = (n) => n*n
console.log(pow(8));

3. Click on the delayed color change exercise

 <script>
        window.onload=function(){
    
    
            let box=document.getElementById("box");
            box.addEventListener("click",function(){
    
    
                //定义一个变量来保存this
                let that=this;
               //定时器
               setTimeout(function(){
    
    
                   //this.style.backgroundColor="black";使用this会报错,因为当前this就是window
                   that.style.backgroundColor="black";
               },2000);
            });

        }
    </script>

ES6 uses arrow functions to write:

  <script>
        window.onload=function(){
    
    
            let box=document.getElementById("box");
            box.addEventListener("click",function(){
    
    
               //定时器
               setTimeout(()=>{
    
    
                //使用箭头函数,因为箭头函数中的this是静态的
                //this始终指向声明作用域下对象的值,就是box
                  this.style.backgroundColor="black";
               },2000);
            });

        }
    </script>

4. Filter even number exercises

<script>
//从数组中返回偶数的元素
let arr=[1,2,3,4,5,6,7,8,9];
let result=arr.filter(function(item){
    
    
  if(item % 2===0){
    
    
   return true;
  }
})
console.log(result);
</script>

ES6 writing:

<script>
//从数组中返回偶数的元素
let arr=[1,2,3,4,5,6,7,8,9];
let result=arr.filter((item)=>(item%2===0))
console.log(result);
</script>

Summary: Arrow functions are suitable for callbacks, timers, and array methods that have nothing to do with this;
arrow functions are not suitable for callbacks, event callbacks, and object methods related to this.

Guess you like

Origin blog.csdn.net/weixin_45636381/article/details/113602697