箭头函数与普通函数的区别

288 阅读1分钟

编写形式

箭头函数存在一个简写体,将一个公式作为函数返回,不包含{...} 和 return。但是,箭头函数不可以换行

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

var B = ()=>{
  console.log('111')
}

var b = new B(); //TypeError: B is not a constructor

箭头函数不绑定arguments,取而代之用rest参数(...)解决

普通函数

function A(a){
  console.log(arguments);
}
A(1,2,3,4,5,8);  //  [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(Symbol.iterator): ƒ]

箭头函数

let B = (b)=>{
  console.log(arguments);
}
B(2,92,32,32);   // Uncaught ReferenceError: arguments is not defined
let C = (...c) => {
  console.log(c);
}
C(3,82,32,11323);  // [3, 82, 32, 11323]

箭头函数没有原型属性

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

function b(){
  return 2;
}

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

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

箭头函数的this

普通函数:

1.this总是代表它的直接调用者, 例如 obj.func ,那么func中的this就是obj

2.在默认情况(非严格模式下,未使用 'use strict'),没找到直接调用者,则this指的是 window

3.在严格模式下,没有直接调用者的函数中的this是 undefined

4.使用call,apply,bind(ES5新增)绑定的,this指的是 绑定的对象

箭头函数:

箭头函数的this指向上下文的this,并且不可被call(),apply(),bind()等更改

参考: 箭头函数与普通函数的区别