ES6中的新增的一种新的函数:()=>{}
以下是区别:
1、语法更简洁
箭头函数
var fn = () =>{
return 123;
}
相当于普通函数
function fn() {
return 123;
}
2、 没有this
普通函数都有自己的this值
const obj = {
a: function() { console.log(this) },
b: {
c: function() {console.log(this)}
}
}
obj.a() // 打出的是obj对象, 相当于obj.a.call(obj)
obj.b.c() //打出的是obj.b对象, 相当于obj.b.c.call(obj.b)
箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。
const obj = {
a: function() { console.log(this) },
b: {
c: () => {console.log(this)}
}
}
obj.a() //没有使用箭头函数打出的是obj
obj.b.c() //打出的是window对象!!
3、不能使用new
箭头函数作为匿名函数,故不能作为构造函数,不能使用new
var fn = ()=>{
count:1
}
var p = new fn(); // TypeError: p is not a constructor
4、不绑定arguments,用rest参数...解决
/*常规函数使用arguments*/
function test1(a){
console.log(arguments);
}
/*箭头函数不能使用arguments*/
var test2 = (a)=>{console.log(arguments)}
/*箭头函数使用reset参数...解决*/
let test3=(...a)=>{console.log(a[1])}
test1(1); // 1
test2(2); // ReferenceError: arguments is not defined
test3(33,22,44); // 22
5、箭头函数没有原型属性
var a = ()=>{
return 1;
}
function b(){
return 2;
}
console.log(a.prototype);//undefined
console.log(b.prototype);//object{...}
网友评论