首页 > 其他 > 详细

ES6之 02.箭头函数

时间:2020-06-13 12:06:58      阅读:45      评论:0      收藏:0      [点我收藏+]

索引

基本规则

  • 删掉一个function关键字
  • 多个参数,分隔
  • 没有参数加括号
  • 1个参数可选择(括号的有无)
const numbers=[5,6,13,0,1,2]
const double=numbers.map(function (number) {
    return 2*number;
})
//1个参数时可带括号或者不带括号
const double1=numbers.map((number)=>{
    return 2*number;
})

const double2=numbers.map(number=>{
    return 2*number
})

//隐式返回
const double3=numbers.map((number)=>2*number);

//大于1个参数
const  double4=numbers.map((number,i)=>`${i}:${number}`)

//无任何参数

const  double5=numbers.map(()=>`hello`)

匿名函数

const greet=(name)=>{
    console.log(`hello ${name}`)
}
greet("hk")

箭头函数的this指向

  • 箭头函数无自己的this,this继承自父作用域
  • 词法作用域(定义时指定而非运行时指定)
const Jelly={
        name:‘Jelly‘,
        hobbies:["coding","music",‘reading‘],
        printHobbies:function(){
            //console.log(this);//指向Jelly对象
            this.hobbies.map(function(hobby){
                //console.log(this)  //这个函数独立调用时this指向window
                console.log(`${this.name} loves ${hobby}`); //这里的this.name为空的
            })
        }
    }
    Jelly.printHobbies()
    //传统修改
    const Jelly1={
        name:‘Jelly‘,
        hobbies:["coding","music",‘reading‘],
        printHobbies:function(){
            const self=this;
            this.hobbies.map(function(hobby){
                console.log(`${self.name} loves ${hobby}`);
            })
        }
    }
    Jelly1.printHobbies();
    //ES6里

    const Jelly2={
        name:‘Jelly‘,
        hobbies:["coding","music",‘reading‘],
        printHobbies:function(){

            this.hobbies.map(hobby=>{
                console.log(`${this.name} loves ${hobby}`);
            })
        }
    }
    Jelly2.printHobbies();

不宜使用的场景

1.作为构造函数,一个方法需要绑定到对象
const Person=function (name,points) {
    this.name=name
    this.points=points;
}
const Person1=(name,points)=>{
    this.name=name
    this.points=points;
}
const  p=new Person(‘hk‘,100)
//const  p1=new Person1(‘hk1‘,90);//Uncaught TypeError: Person1 is not a constructor
Person.prototype.updatePoints=()=>{
    console.log(this) //指向window
    this.points++
}
2.当真的需要this的时候
const button=document.querySelector(".zoom")

button.addEventListener("click",function(){ //这里不该使用箭头函数
    this.classList.add(‘roate‘);
    setTimeout(()=>{  //这里需要继承上级的this所以用箭头函数
        this.classList.remove(‘roate‘)
    },2000)

})
3.需要arguments对象时
const sum=function(){  //如果写成箭头函数,没有arguments对象报错
    return Array.from(arguments).reduce(
        (preSum,value)=>preSum+value,0
    )
}
//array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

ES6之 02.箭头函数

原文:https://www.cnblogs.com/HKUI/p/13112077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!