ES6箭头函数和js普通函数的区别整理

蛰伏已久 蛰伏已久 2019-10-24

this指向

普通函数的this指向为:谁调用它this就指向谁,this被不同对象调用是会变的

箭头函数的this指向为:声明该箭头函数时,外层第一个普通函数的this指向谁就固定为谁,不会改变

1
2
3
4
5
6
7
8
9
10
11
12
function foo() {
    console.log(this)
}
 
const obj = {
    a: 2,
    foo: function(){console.log(this)}
}
foo()  //this指向为window
obj.foo() //this指向为对象obj
let foo2 = obj.foo
foo2()  //this指向为window
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let foo = ()=> {
    console.log(this)
}
 
const obj = {
    a: 2,
    foo: function () {
         
        return ()=>{console.log(this)}
    }
}
foo()  //this指向window
obj.foo()()  //this指向对象obj
let foo2 = obj.foo()
foo2()  //this指向对象obj

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

1
2
3
4
5
6
7
8
9
10
11
function foo() {
    console.log(this)
}
 
new foo()  //window
 
 
let foo2 = ()=>{
    console.log(this)
}
new foo2() //报错 Uncaught TypeError: foo2 is not a constructor

箭头函数不绑定arguments,用rest参数...解决

1
2
3
4
5
6
7
8
9
10
11
function foo() {
    console.log(arguments)
}
 
foo(1,2,3)  //[1,2,3]
 
 
let foo2 = ()=>{
    console.log(arguments)
}
foo2(1,2,3)  // 报错 Uncaught ReferenceError: arguments is not defined

我们可以使用展开符来获取参数

1
2
3
4
let foo2 = (...arguments)=>{
    console.log(arguments)
}
foo2(1,2,3) //[1,2,3]

箭头函数使用bind、call、apply无效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var a = 1
var obj={
    a:2
}
 
function foo() {
    console.log(this.a)
}
 
foo()  //1
foo.call(obj) //2,输出obj.a
 
 
 
let foo2 = ()=>{
    console.log(this.a)
}
foo2()  //1
foo2.call(obj) //1,仍然输出window.a

箭头函数没有原型

1
2
3
4
5
6
7
8
9
var a = ()=>{  
    return 1;
}
function b(){  
    return 2;
}
 
console.log(a.prototype);//undefined
console.log(b.prototype);//object{...}

箭头函数不能当做Generator函数,不能使用yield关键字

箭头函数更简洁,适合写一些简单函数

分享到

点赞(0)