Javascript 箭头函数

Javascript 箭头函数

Javascript箭头函数不仅是“速写”代码的小事情。通常场景为我们需要写一个小函数,然后在其他地方执行。

举例:

  • arr.forEach(func) – func 需要针对数组的每个元素执行.
  • setTimeout(func) – func 在内置的调度计划中执行.
  • …等.

    创建一个函数并将它传递到某个地方是JavaScript的风格。 并且有些函数,我们通常希望保留当前上下文。

箭头函数没有this对象

我们知道对象方法中有this,箭头函数没有this,如果在箭头函数中访问this,将获得外部对象。

举例,我们使用箭头函数遍历对象中的方法:

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(
      student => alert(this.title + ': ' + student)
    );
  }
};

group.showList();

forEach函数中,使用了箭头函数,this.title正处于showList方法中,所以结果为:group.title.

如果我们使用正常函数,会产生错误:

let group = {
  title: "Our Group",
  students: ["John", "Pete", "Alice"],

  showList() {
    this.students.forEach(function(student) {
      // Error: Cannot read property 'title' of undefined
      alert(this.title + ': ' + student)
    });
  }
};

group.showList();

错误是因为forEach中运行的函数带有this=undefined,所以打算访问undefined.title造成错误。
箭头函数没有错误,是因为它们没有this对象。

箭头函数不能和new一起运行

没有this自然意味着另外的限制:箭头函数不能使用构造器,不能使用new去调用。

箭头函数VS绑定
箭头函数=>与使用bind(this)方式调用正常函数有一些区别:

  • .bind(this)创建了函数的绑定对象。
  • 箭头函数=>不创建任何绑定,函数简单到没有this,查找this和正常变量查找方式一样:在外部词法环境。

箭头函数没有 “arguments” 对象

箭头函数没有“arguments” 变量。

当我们需要前一个调用的当前this和arguments时,这时一个伟大的设计。
举例,defer(f,ms)获得一个函数并返回包装函数,其延迟ms毫秒调用输入函数。

function defer(f, ms) {
  return function() {
    setTimeout(() => f.apply(this, arguments), ms)
  };
}

function sayHi(who) {
  alert('Hello, ' + who);
}

let sayHiDeferred = defer(sayHi, 2000);
sayHiDeferred("John"); // Hello, John after 2 seconds

通用的效果,没有使用箭头函数如下:

function defer(f, ms) {
  return function(...args) {
    let ctx = this;
    setTimeout(function() {
      return f.apply(ctx, args);
    }, ms);
  };
}

我们不得不创建额外的变量args和ctx,为了在setTimeout里面的函数可以获得到它们。

总结

箭头函数:

  • 没有 this.
  • 没有 arguments.
  • 不能使用 new调用.
  • (也没有super, 这里没有细说明,继承章节会说明).

That’s because they are meant for short pieces of code that does not have their own “context”, but rather works in the current one. And they really shine in that use case.

因为箭头函数主要为了没有自己上下文的短片段代码,相当于在当前上下文中工作,这样场景比较方便。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值