面试总结:箭头函数和普通函数的区别

925 阅读2分钟

前四项是箭头函数没有的,后几项是与普通函数的对比
如有问题请指正(小菜鸟眼巴巴~期盼求教大神们)

1. 箭头函数不能Generator函数,不能使用yeild关键字。

yield 关键字通常不能在箭头函数中使用(除非是嵌套在允许使用的函数内)。因此,箭头函数不能用作函数生成器。

2. 箭头函数不具有prototype原型对象。

var Foo = () => {};
console.log(Foo.prototype); // undefined

3. 箭头函数不具有super。

没有prototype自然也不能通过super来访问原型的属性,所以箭头函数也是没有super的

4. 箭头函数不具有new.target。

ES6 通过new.target 来判断是否使用new,箭头函数不能使用new创建,自然没有new.target (扩展:为什么不能通过new创建箭头函数)

new操作符的执行过程:

  • 创建一个全新的对象
  • 将创建的对象的原型指向构造函数的 prototype
  • 执行构造函数并将 this 执行新创建的对象
  • return结果 因为箭头函数没有prototype,也没有自己的this指向,所以不能通过new来创建

5. this指向不同

箭头函数的 this 永远指向其上下文的 this ,任何方法都改变不了其指向,如 call() , bind() , apply() vs 在普通函数中,this总是指向调用它的对象,如果用作构造函数,this指向创建的对象实例; 在严格模式下的函数调用下,this指向undefined;如果该函数是一个对象的方法,则它的this指针指向这个对象

var b = 11 
function a(h) { 
  let b = 10 
  let f = () => {
    let result = h + this.b 
    return result 
  } 
  console.log(f()) //14 
  console.log(f.call(b, h)) //14 
} 
a(3)

6. 创建方式不同

箭头函数不能用于构造函数,不能使用new, 会报错: TypeError: xxx is not a constructor

var Foo = () => {};
var foo = new Foo();

capture_20210822113345836.bmp

7. 只能是匿名函数

普通函数可以有匿名函数,也可以有具体名函数,但是箭头函数都是匿名函数

8. 函数参数不绑定arguements,用rest参数...解决

每一个普通函数调用后都具有一个arguments对象,用来存储实际传递的参数。但是箭头函数并没有此对象。

var arguments1 = [1, 2, 3];

var arr = () => arguments1[0];

arr() //1

function foo(n) {
  var f = () => arguments[0] + n; 
  // 隐式绑定 foo 函数的 arguments 对象. arguments[0] 是 n,即传给foo函数的第一个参数
  return f();
}

foo(1); // 2
foo(2); // 4
foo(3); // 6
foo(3,2);//6

function foo(arg) {
  var f = (...args) => args[0];
  return f(arg);
}
foo(1); // 1

function foo(arg1,arg2) {
    var f = (...args) => args[1];
    return f(arg1,arg2);
}
foo(1,2);  //2