Es6-箭头函数

125 阅读2分钟

①箭头函数

1.认识箭头函数

const add = (x, y) => {
  return x + y;
};
console.log(add(1, 1));

2.箭头函数的结构

const/let 函数名=参数=>函数体

3.如何将一般函数改写成箭头函数

声明形式

function add() {}

声明形式-> 函数表达式形式

const add = function () {};

②.箭头函数的注意事项

1.单个参数

单个参数可以省略圆括号

const add=x=>{
    return x+1
}
const add=(x)=>{
    return x+1
}
console.log(add(1));

无参数或多个参数不能省略圆括号

 const add=()=>{
     return 1+1
 }
 const add=(x,y)=>{
     return x+y
 }
 console.log(add());

2.单行函数体

单行函数体可以同时省略{}和return

const add=(x,y)=> x+y;
console.log(add(1,1));

多行函数体不能再化简了

const add=(x,y)=>{
    const sum=x+y;
    return sum;
}

3.单行对象

 const add=(x,y)=>{
     return {
         value:x+y
     }
 }
 const add=(x,y)=>({ value:x+y  })

如果箭头函数返回单行对象,可以在{}外面加上(),让浏览器不再认为那是函数体的花括号

③this指向

"use strict" 注:严格模式在开头或者在函数体内才会生效,在中间夹着不会生效

1.全局作用域中的this指向

console.log(this); //window

2.一般函数(非箭头函数)中的this指向

add()
//"use strict"
function add() {
console.log(this);
}
// 严格模式就指向undefined
add(); //undefined->window(非严格模式下)
window.add(); //非严格下就是类似于这样
 
const calc={
    add:add
};
const adder=calc.add;
adder();//undefined->window(非严格模式下)
document.onclick=function(){
    console.log(this);//document
}

function Person(username){
    this.username=username;
    console.log(this);
}
const p =new Person('Alex')

只有在函数调用的时候this指向才确定,不调用的时候不知道指向谁

this指向和函数在哪调用没关系,只和谁调用有关

3.箭头函数中的this指向

箭头函数没有自己的this

const calc={
    add:()=>{
        console.log(this);
    }
}
calc.add()//window

4.练习

    const calc={
        add :function(){
            const adder=()=>{
                console.log(this);
            }
            adder();
        }
    }
    calc.add() //calc
    const addFn=calc.add;
    addFn() //undefined->window

④不适用箭头函数的场景

1.作为构造函数

箭头函数没有this

 const Person =()=>{}
  new Person()//报错

2.需要this指向调用对象的时候

     document.addEventListener(
       "click",
      ()=>{
        console.log(this);//window
      },
        false
    );

3.需要使用arguments的时候

  const add = () => console.log(arguments);
  add();//报错
  剩余函数
  function add(){
    console.log(arguments);
  }
  add(1,2,3,4,5)

⑥箭头函数的应用

<body>
    <button id="btn">开始</button>
    <span id="result">0</span>
    <script>
      const btn = document.getElementById("btn");
      const result = document.getElementById("result");

      const timer = {
        time: 0,
        start: function () {
          btn.addEventListener(
            "click",
            () => {
              setInterval(() => {
                console.log(this);
                this.time++;
                result.innerHTML = this.time;
              }, 1000);
            },
            false
          );
        },
      };
      timer.start();
    </script>
  </body>