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

2017-08-06  本文已影响0人  他在发呆

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);
}
上一篇 下一篇

猜你喜欢

热点阅读