JavaScript之箭头函数

1.箭头函数

ES6新增的一种函数,箭头函数。用一个箭头来定义函数。

let fn = ( ) => {  }

上面的箭头函数相当于

 let fn = function () { }

2.声明箭头函数

 let fn = (形参) => {  函数体 }

3.调用函数

fn(实参)

4.箭头函数的简写

①省略小括号,当形参有且只有一个的时候

    let add = (n) => {
      return n + n
    }
    console.log(add(2))  //4

②省略花括号,当代码体只有一条语句的时候

    let pow = (n) => n * n
    console.log(pow(3))  //9

5.箭头函数的特性

①this是静态的,始终指向函数声明时所在区域下的this

②不能作为构造函数实例化对象

    let Person = (name, age) => { this.name = name , this.age = age }
    let p = new Person('zs', 18)
    console.log(p)//报错Person is not a constructor

③不能使用argnments变量(保存实参)

 普通函数

    function fun(a, b) { console.log(arguments) }
    fun(1, 2)  //Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ]

箭头函数

    let fn = (a, b) => { console.log(arguments) }
    fn(1, 2)  //arguments is not defined

6.应用场景

①点击div,2s后变色

    let div = document.querySelector('div')
    div.addEventListener('click', function () {
      setTimeout(function () {
        this.style.backgroundColor = 'pink'
      }, 2000)
    })

我们这样使用this来改变style的属性,是不行的。因为这里的this有指向问题,点击之后会报出一个‘Cannot set properties of undefined (setting 'backgroundColor')’的错误。控制台打印一下this,它指向的是window,在这里的window是没有style属性的,所以style.backgroundColor 就会报错。

此时就可以使用到箭头函数来实现这个需求。

    let div = document.querySelector('div')
    div.addEventListener('click', function () {
      setTimeout(() => {
        // console.log(this)
        this.style.backgroundColor = 'pink'
      }, 2000)
    })

此时就不会出现任何错误。因为使用了箭头函数,箭头函数的this是静态的,它指向在声明时所在作用域下的this的值,他是在外层作用域下声明的,所以this指向的是外层函数这个事件的调用者div,就可以找到div并修改它的style.backgroundColor值。

②从数组中返回偶数的元素

我们使用普通函数时:

    let str = [1, 22, 45, 76, 36, 47, 19]
    let result = str.filter(function (item) {
      if (item % 2 === 0) {
        return true
      } else {
        return false
      }
    })
    console.log(result)//[22, 76, 36]

 使用箭头函数,简化了代码书写:

    let str = [1, 22, 45, 76, 36, 47, 19]
    let result = str.filter(item => { item % 2 === 0 })
    console.log(result)//[22, 76, 36]

总结:箭头函数适合与this无关的回调,定时器、数组的方法回调。不适合与this有关的回调,事件回调、对象的方法。

猜你喜欢

转载自blog.csdn.net/weixin_70443954/article/details/128376359