美文网首页
Arrow Function(箭头函数)

Arrow Function(箭头函数)

作者: 灯火葳蕤234 | 来源:发表于2019-03-16 00:19 被阅读0次

举例:

const square = function(number) {
  return number * number;
}
consr square = (number) => {
  return number * number;
  }
  • 我们可以删掉function关键字,然后在参数和函数体之间加一个剪头
  • 如果只有一个参数,可以不用括号,如果没有参数,就需要加一个空括号对。
  • 如果我们的函数体只有一行代码返回一个值,我们可以更加缩减书写代码,我们可以去掉大括号和return关键字,写成这样:
consr square = (number) => number * number;
  • 剪头函数让代码更简明易懂。
  • 使用场景(筛选jobs对象,当每个job的isActive是真的的时候)
const jobs = [
  { id: 1, isActive: true },
  { id: 2, isActive: true },
  { id: 3, isActive: false },
];
const activeJobs = jobs.filter(function(job) { return job.isActive; });
const activeJobs = jobs.filter(job => job.isActive );

Arrow Function And This

  • 有一点需要明白的是,剪头函数不重新绑定this
const person = {
  talk() {
    console.log('this',this);
  }
};
person.talk();

此时,打印的是person的引用,因为this现在是绑定到person对象的。
如果将打印信息放到setTimeOut函数会怎样?

const person = {
  talk() {
    setTimeOut(function (){
      console.log('this',this);
    },1000);
  }
};
person.talk();
  • 运行,我们得到了window对象,而不是person对象。原因是setTimeOut中传入的匿名函数不属于任何对象,是一个孤立的函数。
  • 我们已经知道,当我们以一个孤立函数的方式调用函数的时候,默认情况下,this返回的是window全局对象。我们单独调用函数未得到window而是得到undefined,是因为在那种特定情况下,当我们引用一个对象中的方法时,严格模式就介入了,并且将this设置为未定义。
  • 但是现在这个特定的情况,它是回调函数,严格模式并不会重新设置window的行为,所以我们通过console.log('this',this);得到了window对象。

那我们怎么在回调函数中得到person对象呢?

  • 在很久以前,我们声明一个变量来保存此时的this,我们在回调函数外部来定义这个变量,然后在回调函数中使用哪个中间变量去访问person.
const person = {
  talk() {
    var self = this;
    setTimeOut(function (){
      console.log('self',self);
    },1000);
  }
};
person.talk();

运行,我们就得到了person对象

  • 上面是以前的做法,现在有了剪头函数就不用这样了。因为,剪头函数不重绑定this,换句话说,如果我们在setTimeOut中使用剪头函数替换回调匿名函数,它就会继承this的设置。
const person = {
  talk() {
    setTimeOut(()=> {
      console.log('this',this);
    },1000);
  }
};
person.talk();

运行,我们可以看到this指向了person对象。我们运用剪头函数不重绑定this的特性,实现了在回调函数中得到person对象。

相关文章

网友评论

      本文标题:Arrow Function(箭头函数)

      本文链接:https://www.haomeiwen.com/subject/ekadmqtx.html