ES6 箭头函数

1、箭头函数都是匿名函数,无function 声明。

let func = num => {console.log(num)};

func(1) //1

2.箭头函数没有自己的this,它的this继承自其父作用域。

箭头函数的this永远指向其父作用域,任何方法都改变不了,包括call,apply,bind。

//1没有使用箭头函数
const jelly = {
    name: "jelly",
    hobbies: ['coding', 'sleeping', 'reading'],
    printHobbies: function () {
        var self = this;
        this.hobbies.map(function (hobby) {
            console.log(self.name, hobby);
        })
    }
}
jelly.printHobbies();
//如上,在没有使用箭头函数时,要想调用name值,需要在function中声明self,
// 然后在map()函数中调用self.name才能调用,如果在map()函数中直接调用this,则该map()中的this值为window对象。


//2.使用箭头函数
const Tom = {
    name: "Tom",
    hobbies: ['coding', 'sleeping', 'reading'],
    printHobbies: function () {
        this.hobbies.map(hobby => {
            console.log(this.name, hobby);
        })
    }
}
Tom.printHobbies();
// 如上,当使用箭头函数时:this继承自其父作用域,所用this.name能被调用

3.箭头函数不能作为构造函数,不能使用new

const Person = (name, age) => {
    this.name = name;
    this.age = age;
}
const Bom = new Person("Bom", 18); //Person is not a constructor 
// 因为使用箭头函数不能用于构造函数因为箭头函数本身没有属于自己的this,所以箭头函数不可以当做构造函数,

4.绑定事件也不适合使用箭头函数

const div = document.querySelector(".box1");
div.addEventListener("click",()=>{
    this.classList.add("in");
    setTimeout(()=>{
        this.classList.remove("in");
    },2000)
})
//默认情况下,click回掉函数会绑定到触发事件的元素上,
//但因为是箭头函数,箭头函数不会绑定到触发事件的元素上,此时this即为外层this,即this为window。

5.当需要使用arguments参数时,不能使用箭头函数,因为 箭头函数没有arguments,caller,callee

const B = (b) => {
    console.log(arguments);
}
B(2, 92, 32, 32);   // arguments is not defined

6.箭头函数没有原型

const a = () => {
    return 1;
}

function b() {
    return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   // {constructor: ƒ}

总结:

箭头函数优势
1.隐式返回
2.箭头函数都是匿名函数,无function声明
3.箭头函数没有自己的this,它的this继承自其父作用域。

不适宜箭头函数的场景
1.不能作为构造函数
2.定义对象的方法时,不适合使用箭头函数,因为箭头函数中的this值继承自父域,如果使用箭头函数定义对象方法,则this会指定为window。
3.绑定事件也不适合使用箭头函数,默认情况下,click回掉函数会绑定到触发事件的元素上,
但因为是箭头函数,箭头函数不会绑定到触发事件的元素上,此时this即为外层this,即this为window。
4.当需要使用arguments参数时,不能使用箭头函数,因为 箭头函数没有arguments,caller,callee
5.箭头函数没有原型属性

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值