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

138 阅读2分钟
1. 箭头函数不会创建自的 this, 所以它没有自已的 this, 它只会从自已的作用域链的上一层继承 this

箭头函数没有自已的 this, 它会捕获自已在定义时所处的外层执行环境的 this, 并继承这个 this 的值,所以箭头函数中 this 的指向在它定义时*就被确定了,之后永远不会改变

var id = 'Global';

function fun1() {
    // setTimeout中使用普通函数
    setTimeout(function(){
        console.log(this.id);
    }, 2000);
}

function fun2() {
    // setTimeout中使用箭头函数
    setTimeout(() => {
        console.log(this.id);
    }, 2000)
}

fun1.call({id: 'Obj'});     // 'Global'

fun2.call({id: 'Obj'});     // 'Obj'

fun1 的 setTimeout 中使用普通函数,2 秒后执行函数,这时函数是在全局作用域中执行的,所以 this 指向 window 对象, this.id 就指向全局变量 id, 所以输出 'Global'

fun2 的 setTimeout 中使用的是箭头函数,它会捕获外层执行环境的 this, fun2调用提 this 被改变到了 {id: 'Obj'}, 所以输出 'Obj'

示例2:

var id = 'GLOBAL';
var obj = {
  id: 'OBJ',
  a: function(){
    console.log(this.id);
  },
  b: () => {
    console.log(this.id);
  }
};

obj.a();    // 'OBJ'
obj.b();    // 'GLOBAL'
2. .call()/.apply()/.bind() 无法改变箭头函数的 this 指向
var id = 'Global';
// 箭头函数定义在全局作用域
let fun1 = () => {
    console.log(this.id)
};

fun1();     // 'Global'
// this的指向不会改变,永远指向Window对象
fun1.call({id: 'Obj'});     // 'Global'
fun1.apply({id: 'Obj'});    // 'Global'
fun1.bind({id: 'Obj'})();   // 'Global'
3.箭头函数不能作为构造函数使用

我们选来看构造函数 new 时做了什么?

  1. js 内部先生成一个对象
  2. 把函数中的 this 指向应该对象
  3. 然后执行构造孙数中的语句
  4. 返回对象实例

但是!!箭头函数没有自已的 this , 它的 this 其实是继承了外层执行环境的 this, 且 this 指向不会被改变,所以箭头函数不能被用作构造函数使用,否则用 new 调用时会报错。

4. 箭头函数没有自已的 argumnets
5. 箭头函数没有原型 prototype
let sayHi = () => {
    console.log('Hello World !')
};
console.log(sayHi.prototype); // undefined
6. 箭头函数不能作为 Generator 函数,不能使用 yeild 关键字