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

1. this指向

箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

        function make () {
            return () => {
                console.log(this)
            }
        }
        make()() // window
        const testFunc = make.call({ name: 'foo' });
        testFunc(); // { name: 'foo' }
        testFunc.call({ name: 'bar' }); // { name: 'foo' }
        testFunc(); // { name: 'foo' }
        const testFunc2 = make.call({ name: 'too' });
        testFunc2() // { name: 'too' }

如果要绑定this对象

function make () {
  var self = this;
  return function () {
    console.log(self);
  }
}

方法二
function make () {
  return function () {
    console.log(this);
  }.bind(this);
}
  • 箭头函数不可以使用类似于arguments对象(super(ES6),new.target(ES6)……),该对象在函数体内不存在。如果要用,可以用Rest参数代替。

  • 不可以使用yield命令,因此箭头函数不能用作Generator函数。

  • 箭头函数不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容