ES6 箭头函数和普通函数有哪些区别 ?

ES6 中的 箭头函数 和 普通函数 有哪些区别 ?


  • 箭头函数没有 prototype(原型):
function test1 () {
	console.log(test1.prototype)
}
test1() //普通函数 constructor: f test1()
const test2 = () => {
	console.log(test2.prototype)
}
test2() //箭头函数 undefined;
  • this 指向规则不同 :

箭头函数 :它没有 prototype(原型),所以它本身没有 this,箭头函数会捕获其所在上下文的 this 值,作为自己的 this值。即箭头函数的作用域会继承自外围的作用域。(箭头函数的 this 在定义的时候继承自外层第一个普通函数的 this,如果箭头函数外层没有普通函数,严格模式和非严格模式下它的 this 都会指向 window (全局对象))任何方法都改变不了其指向,如使用 call(),bind(),apply() 方法等。但是可以通过改变它外层 this 指向来间接的改变。

普通函数 :this 指向调用它的那个对象,可以使用 call(),bind(),apply() 等方法重新指定 this 的指向。

var obj = {
a: 10,
b: () => {
	  console.log(this.a); // undefined 
	  console.log(this); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
    },
c: function() {
	  console.log(this.a); // 10
	  console.log(this); // {a: 10, b: ƒ, c: ƒ}
    }
}
obj.b(); 
obj.c();
var obj = {
	a: 10,
    b: function(){
	   console.log(this.a); //10
	  },
	c: function() {
	     return ()=>{
	       console.log(this.a); //10
	    }
      }
}
obj.b(); 
obj.c()();
  • 箭头函数是匿名函数,不能作为构造函数,不能使用new
let test3 = () => {
    console.log(this)  
 }
 let test4 = new test3()
/*Error: Uncaught TypeError: test3 is not a constructor*/
  • 箭头函数不绑定arguments,取而代之用 rest 参数 …x 解决

ES6 引入reset 参数(形式为 …变量名),用于获取函数的多余参数,这样就不需要使用 arguments 对象了。reset 参数搭配的变量是一个数组。

箭头函数的 this 指向全局,使用 arguments 会报未声明的错误,箭头函数的 this 指向普通函数时,它的 argumens 继承于该普通函数。

function A (a) {
    console.log(arguments)//1,2,3,4
  }
A(1,2,3,4);
	  
const B = (...b) => {
    console.log(b)//5,6,7,8
  };
B(5,6,7,8);

const C = (c) => {
    console.log(arguments)// Uncaught ReferenceError:arguments is not defined
  };
C(9,10,11,12);

 

  • 箭头函数不能换行
var a = () 
          => 1;//SyntaxError:Unexpected token
  • 箭头函数不能当做 Generator 函数,不能使用 yield 关键字 
  • 箭头函数不支持重命名函数参数,普通函数的函数参数支持重命名
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值