箭头函数(Arrow Function)

ES6中箭头函数的好处:

一、简明的语法

1):删掉function关键字加上=>

2):没有参数加括号

3):一个参数可以选择不加上()

4):多个参数必须加(),并且参数之间用逗号分隔。

二、隐式返回

//箭头函数返回一个值。

//如果箭头后面执行的代码只有一句且有返回值,可以省略{}和return关键字。

const numbers = [1, 2, 3, 4, 5]

const name = numbers.map(number => number * 2)

//匿名箭头函数,如果有返回值必须加上return关键字。

const info = () => {return 1+2}

//此处需要在接收的变量上加上()来进行方法的调用。

console.log(info())

//匿名箭头函数时并带参。

const numbers = [1, 2, 3, 4, 5]

const info = (numbers) => {

    return numbers.map(number => number * 2)

  }

  console.log(info(numbers))

//总结:箭头函数相当于匿名函数,并且简化了函数定义。

//箭头函数有两种格式,一种只包含一个表达式,连{ ... }和return都省略掉了。

//还有一种可以包含多条语句,这时候就不能省略{ ... }和return。

三、箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值。

const Jelly = {

    name: 'Jelly',

    age: 22,

    hobbies: ['Coding', 'Sleeping', 'Reading'],

    hobbiesInfo: function () {

      console.log(`第一个函数的this是${this}`)

      this.hobbies.map(function (hobby) {

        console.log(`第二个函数的this是${this}`)

        console.log(`${this.name} loves ${hobby}`)

      })

    }

  }

  Jelly.hobbiesInfo()

//第一个函数的this是[object Object]

//第二个函数的this是[object Window]

将map括号内的函数更改为箭头函数。


const Jelly = {

    name: 'Jelly',

    age: 22,

    hobbies: ['Coding', 'Sleeping', 'Reading'],

    hobbiesInfo: function () {

      console.log(`第一个函数的this是${this}`)

      this.hobbies.map(hobby => {  //此处为更改后的代码

        console.log(`第二个函数的this是${this}`)

        console.log(`${this.name} loves ${hobby}`)

      })

    }

  }

  Jelly.hobbiesInfo()

//第一个函数的this是[object Object]

//第二个函数的this是[object Object]

箭头函数不宜使用的场景

一、箭头函数是匿名函数,不能作为构造函数,不能使用new


const Person = (name,age) =>{

    this.name = name

    this.age = age

  }

  const jack = new Person('jack',26)

//Uncaught TypeError: Hello is not a constructor

二、创建对象方法时,应该使用function()

const Person = function(name,age){

    this.name = name

    this.age = age

  }

  const Jack = new Person('jack',26)

  Person.prototype.updateAge = () => {

    console.log(this)  //Window?{postMessage: ?, blur: ?, focus: ?, close: ?, parent: Window,?…}

    this.age++

    console.log(this.age)

  }

  Jack.updateAge()  //NaN

  /**

  *因为箭头函数并不会进行this绑定,所以这时的this值是window,所以输出NaN

  * 所以当我们想要创建一个对象方法时,应该使用function(),

  * function会在运行时对this进行绑定。

  */

三、绑定事件的时候


  /**

  * 绑定事件当你需要this值的时候,不要用箭头函数。

  */

  const button = document.querySelector('button')

    button.addEventListener('click',function(){

    //由于箭头函数不绑定this

    //由于function()函数由谁调用,this就是谁。

    //所以箭头函数应该改成function()。this  = [object HTMLButtonElement]

      this.classList.add('in')

      setTimeout(() => {

      //由于function()是在运行时绑定this值的,

      //此时由window调用function()函数,this就指向了[object Window]

      //要想沿用上下文中的this。此处应改成箭头函数 this  = [object HTMLButtonElement]

        this.classList.remove('in')

      },2000)

    })

四、箭头函数不绑定arguments,取而代之用可变参数解决。

function toInfo(params){

      console.log(arguments)

  }

  toInfo(1,2,3,4,5)

  //Arguments(5)?[1, 2, 3, 4, 5, callee: ?, Symbol(Symbol.iterator): ?]

  const toShow = (params) =>{

    console.log(arguments)

  }

  toShow(1,2,3,4,5)

  //Uncaught ReferenceError: arguments is not defined

  const toDescription = (...params) =>{

    console.log(params)

  }

  toDescription(1,2,3,4,5,6)

//(6)?[1, 2, 3, 4, 5, 6]

五、箭头函数没有原型属性箭头,函数不能当做Generator函数,不能使用yield关键字

总结:

1:箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply()

2:普通函数的this指向调用它的那个对象。

3:当你不需要用构造函数创建对象,不需要创建对象方法,不需要为元素绑定事件时,不需要绑定arguments时。我们就可以尽情的用箭头函数啦 。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容