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

2020-07-28  本文已影响0人  HS_d119

1、箭头函数是匿名函数,不能作为构造函数,不能使用new

        let a = () => { console.log(1) }

        a()

        new a()    // TypeError: a is not a constructor


2、箭头函数不绑定arguments(用于指向调用者传入的所有参数),取而代之用rest参数...解决

        function A(a, b, c, d) {

                console.log(arguments); // [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]

       }

       A(1, 2, 3, 4)

        let B = (...r) => {

                console.log(r); // [5, 6, 7]

        }

        B(5, 6, 7)


3、this的作用域不同

    a、普通函数根据它是被如何调用的来定义这个函数的this值

    b、箭头函数没有自己的 this,当在内部使用了 this时,它会指向最近一层作用域内的 this

          如果是该函数是一个构造函数,this指针指向一个新的对象

          在严格模式下的函数调用下,this指向undefined

          如果是该函数是一个对象的方法,则它的this指针指向这个对象


4、箭头函数没有原型属性

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

        function b(){ return 2; }

        console.log(a.prototype);  // undefined

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


5、 yield 关键字通常不能在箭头函数中使用(除非是嵌套在允许使用的函数内)

上一篇 下一篇

猜你喜欢

热点阅读