ES6必知,箭头函数与普通函数的区别。

1. 箭头函数没有prototype(原型),所以箭头函数本身没有this

let a = () =>{};
console.log(a.prototype); // undefined

2. 箭头函数的this指向在定义的时候继承自外层第一个普通函数的this。

下面栗子中在一个函数中定义箭头函数,然后在另一个函数中执行箭头函数。

let a,
    barObj = {
        msg: 'bar的this指向'
    };
fooObj = {
    msg: 'foo的this指向'
};
bar.call(barObj); // 将bar的this指向barObj
foo.call(fooObj); // 将foo的this指向fooObj
function foo() {
    a(); // 结果:{ msg: 'bar的this指向' }
}

function bar() {
    a = () => {
        console.log(this, 'this指向定义的时候外层第一个普通函数'); // 
    }; // 在bar中定义 this继承于bar函数的this指向
}

从上面栗子中可以得出两点

  1. 箭头函数的this指向定义时所在的外层第一个普通函数,跟使用位置没有关系。
  2. 被继承的普通函数的this指向改变,箭头函数的this指向会跟着改变

3、箭头函数不能作为构造函数使用

我们先了解一下构造函数的new都做了些什么?

简单来说,分为四步: ① JS内部首先会先生成一个对象; ② 再把函数中的this指向该对象; ③ 然后执行构造函数中的语句; ④ 最终返回该对象实例。

因为箭头函数没有自己的this,它的this其实是继承了外层执行环境中的this,且this指向永远不会随在哪里调用、被谁调用而改变,所以箭头函数不能作为构造函数使用,或者说构造函数不能定义成箭头函数,否则用new调用时会报错!

let Fun = (name, age) => {
    this.name = name;
    this.age = age;
};

// 报错
let p = new Fun('cao', 24);

4、箭头函数没有自己的arguments

箭头函数没有自己的arguments对象。在箭头函数中访问arguments实际上获得的是外层局部(函数)执行环境中的值。

// 例子一
let fun = (val) => {
    console.log(val);   // 111
    // 下面一行会报错
    // Uncaught ReferenceError: arguments is not defined
    // 因为外层全局环境没有arguments对象
    console.log(arguments); 
};
fun(111);
原文地址:https://www.cnblogs.com/magicg/p/12725578.html