js面试题之箭头函数与普通函数的区别

73 阅读1分钟
箭头函数是 ES6 新增的特性,用来简化普通函数的写法,规避普通函数 this 指向的痛点。
1. 箭头函数没有原型对象 prototype,不能作为构造函数使用(不能被 new)
const Person = ()=> {
      console.log(Person.prototype)
}
new Person()

image.png

2.箭头函数没有arguments,可以使用 '...'拿到所有实参的集合数据
const sum = (...args)=> {
     console.log(args)
}
sum(1, 2, 3, 4, 5)

image.png

3. 箭头函数中的this 在定义时就已经被确定,却决于父级的环境
const fn = ()=> {
      console.log(this)
}
fn()

image.png

4.箭头函数不能通过call,apply,bind 方法修改它的 this 指向(会忽略第一个参数,其他功能还是可以正常使用的)
const obj = {
    name: '张三',
    age: 18
}
const Person = (a, b) => {
      console.log(a, b)
}
// Person.call(obj, 1, 2)      // 1, 2
// Person.apply(obj, [1, 2])   // 1, 2
const newFn = Person.bind(obj, 1, 2)
newFn() // 1,2
5.箭头函数不能用作 Generator 函数,不能使用 yield 关键字(function*)
function* fn() {
    yield 'hello'
}
const test = fn()
console.log(test.next())  // {value: 'hello', done: 'false'}