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

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

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

    a()

    let fn = new a()  //报错: Uncaught TypeError: a is not a constructor

2、箭头函数不绑定arguments,取而代之用rest参数...解决(更多详情参阅 ECMAScript 6 入门)

    // arguments变量的写法

        function sortNumbers() {

            return Array.prototype.slice.call(arguments).sort();

        }

    // rest参数的写法

     const sortNumbers = (...numbers) => numbers.sort();

    arguments对象不是数组,而是一个类似数组的对象。所以为了使用数组的方法,必须使用Array.prototype.slice.call先将其转为数组。rest 参数就不存在这个问题,它就是一个真正的数组,数组特有的方法都可以使用

    下面是一个利用 rest 参数改写数组push方法的例子。

    function push(array, ...items) {

        items.forEach(function (item) {

            array.push(item);

            console.log(item);

        });

    }

    var a = []; push(a, 1, 2, 3)

    注意,rest 参数之后不能再有其他参数(即只能是最后一个参数),否则会报错。

    // 报错

    function f(a,...b,c){ // ...}

    函数的length属性,不包括 rest 参数。

    (function(a){}).length     // 1

    (function(...a){}).length     // 0

    (function(a,...b){}).length     // 1

3、this的作用域不同,箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值。

    var obj = {

        a: 10,

        b: () => {

            console.log(this.a); /报错:/ undefined

            console.log(this);  

            // 报错 : Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}

        },

        c: function() {

            console.log(this.a); // 10

            console.log(this); // {a: 10, b: ƒ, c: ƒ}

        }

    }

    obj.b();

    obj.c();

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

    var fun1 = ()=>{

        return 11;

    }

    function fun2(){

        return 22;

    }

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

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

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

你可能感兴趣的:(普通函数和箭头函数的区别)