12

前端笔记(关于箭头函数与普通函数的区别的理解)

 4 years ago
source link: http://www.cnblogs.com/wuhairui/p/12818905.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

大家都知道箭头函数是es6新增的函数声明方式,当然普通函数还是可以继续使用的。我以前一直只知道箭头函数只对this指向有影响,但是没法说清楚具体有哪些影响,因此今天来总结整理一下。

1.普通函数的this指向当前调用者对象。箭头函数的this指向其上下文

let obj={
    a:function(){
        console.log(this)//当前调用者
    },
    b:()=>{
        console.log(this)//上下文
    }
}
obj.a()
obj.b()

2.箭头函数不能作为构造函数,所以也不能new,new就会报错。普通函数可以

jaiIbiM.png!web

veYfY3u.png!web

3.箭头函数不能使用arguments,但可以使用...rest代替。rest参数也能在普通函数中使用,用于函数中传递不定参数

arguments是类数组,需要遍历进行使用。arguments和rest都必须写在最后面。

const A=(...a)=>{
    console.log(a)
}
A(1,2,3,4)//数组

const B=function(){
    console.log(arguments)
}
B(1,2,3,4)//类数组

4.箭头函数没有原型对象,普通函数有

//原型区别
const F=()=>{}
const G=function(){}
console.log(F.prototype)//undefined
console.log(G.prototype)//原型对象

aaIV3u6.png!web

拓展知识:

1.call、apply、bind可以改变普通函数this指向,无法改变箭头函数的this指向

此处使用call后this就不是参数1的对象了,然后自动调用f函数。

apply:参数2传的是数组。bind:重新绑定对象,生成新的函数,需要重新调用

//改变this指向
const f=function(a){
    console.log(this.name+a)
}
f()//undefined
f.call({name:1},2)//3

这个this还是代表上下文,不是那个对象

const F=()=>{
    console.log(this)
}
F.call({a:1})//window

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK