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

箭头函数

箭头函数是一个匿名函数,使用=>连接参数列表和函数体,当函数参数只有一个时可以省略括号,没有参数时不能省略括号,只有一条表达式时可以省略{}和return

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

1. 语法更加简洁清晰

2. 箭头函数不能创建自己的this

  • 箭头函数不会创建自己的this,所以他没有自己的this,他只会从自己的作用域链的上一层继承this
  • 箭头函数的this指向,在它定义时就已经确认了,之后就不能改变了
let id = "Global"
let obj = {
    id: "Obj",
    a: function() {
        console.info(this.id)
    },
    b: () => {
        console.info(this.id)
    }
}

obj.a   // "Obj"
obj.b   // "Global"
// 分析:
// 首先{}对象不能作为执行上下文环境,所以箭头函数中的this是指向window,而window.id就是"Global"
// 普通函数的this指向调用它的对象,也就是obj,obj.id就是"Obj"

3. 箭头函数继承而来的this指向是永远不变的

4. .call()/.apply()/.bind()无法改变箭头函数的this指向

  • .call()/.apply()/.bind()可以动态修改函数执行时的this指向,但是箭头函数的this指向在定义时就确定了,之后就无法改变了

5. 箭头函数不能作为构造函数使用

  • 分析new的过程
    • (1). 生成一个新对象
    • (2). 链接到原型
    • (3). 绑定this
    • (4). 返回新对象
      // 自行封装new
      function create() {
         // 创建一个新的对象
         let obj = new Object()
         // 获取构造函数
         let Con = [].shift.call(arguments)
         // 连接到原型
         obj.__proto__ = Con.prototype
         // 绑定this
         let result = Con.apply(obj, arguments)
         // 返回新的对象
         return typeof result === "object" ? result : obj
      }
      
  • 因为箭头函数没有自己的this,也不能改变this指向,所以就不能作为构造函数使用,否则new就会报错

6. 箭头函数没有自己的arguments

  • 普通函数都有自己的arguments,arguments是一个类数组
    function a () {
     console.info(arguments)
    }
    a(1,2,3)   // arguments[1,2,3]
    
  • 箭头函数可以使用...rest代替arguments
    const a = (...rest) => {
     console.info(rest)
    }
    a(1, 2, 3) // [1, 2, 3]
    

7. 箭头函数没有原型prototype

let sayHi = () => {
    console.info("hello")
}
console.info(sayHi.prototype)  // undefined

8. 箭头函数不能用作Generator函数,也不能使用yield关键字

results matching ""

    No results matching ""