JavaScript箭头函数解决了哪些与范围相关的问题?

JavaScript箭头函数解决了哪些与范围相关的问题?,javascript,ecmascript-6,scope,arrow-functions,Javascript,Ecmascript 6,Scope,Arrow Functions,我听到有人说Javascript箭头函数可以用来“解决一些与范围相关的问题” 到目前为止,我已经知道JavaScript箭头函数的主要优点是保存语法或允许隐式行为 1)Shorter(“sugar”)语法示例: ()=>{...} let myFunction = ()=>{...} 短于: 2)隐式行为,如下面的reduce()示例: let prices = [1, 2, 3, 4, 5]; let result = prices.reduce( (x,y)=> x+y

我听到有人说Javascript箭头函数可以用来“解决一些与范围相关的问题”

到目前为止,我已经知道JavaScript箭头函数的主要优点是保存语法或允许隐式行为

1)Shorter(“sugar”)语法示例:

()=>{...}
let myFunction = ()=>{...}
短于:

2)隐式行为,如下面的
reduce()
示例:

let prices = [1, 2, 3, 4, 5];
let result = prices.reduce( (x,y)=> x+y );
// Reduce data from x to y (reduce needs return, which is included implicitly). Result will be 15 (1+2+3+4+5 are reduced to 15, in this case).

我无法将这些示例和其他示例与范围相关联。我知道在作用域中存在一个问题,即在具有
var
的函数中声明的变量无法继承到子函数,当
const
let
引入时(它们允许这样的继承),这个问题就得到了解决


那么,除了建议使用sugar语法和一些隐式行为之外,arrow函数还需要解决哪些主要的作用域问题呢?

ES6 fat arrow函数不仅可以解决语法简洁、代码可读性差的问题,而且还具有更多的优势。此外,新的Arrow函数是如何绑定或实际上不绑定它自己的函数的。箭头函数在词汇上绑定其上下文,因此这实际上是指原始上下文。现在你的问题是,什么是词汇绑定。让我们试着用简单的例子来理解。考虑一个小的JavaScript代码。

const team = {
  members = ['Ankur','Ranjan'],
  teamName = 'Super Squad',
  teamSummary: function(){
    return this.members.map(function(member){
      return `${member} is on team $(this.teamName)`
    }) 
  }
 }
此代码将抛出TypeError:无法读取未定义的属性“teamName”。您可以使用JavaScript的
bind()
方法来解决此问题,也可以使用
var self=this
并将
this.teamName
更改为
self.teamName
。这两种方法都很好,但您也可以使用箭头函数来解决此问题

const team = {
  members = ['Ankur','Ranjan'],
  teamName = 'Super Squad',
  teamSummary: function(){
  // this === team
  return this.members.map((member) => {
    return `${member} is on team $(this.teamName)`
    }) 
  }
}

那么,“词法this”到底是如何允许我们传递执行上下文的呢?通过使用“词汇范围”。词法作用域只是指它从包含Arrow函数的代码中使用它。

可能重复的Arrow函数没有自己的
this
,因此在用作回调时保留外部
this
上下文。@connexo我假设通过“外部this”您是指最后一个箭头功能之前的最新可用
?@user9303970他指的是闭包,就像它对其他变量一样。这也意味着您不能
将(obj)
绑定到箭头函数。
const team = {
  members = ['Ankur','Ranjan'],
  teamName = 'Super Squad',
  teamSummary: function(){
  // this === team
  return this.members.map((member) => {
    return `${member} is on team $(this.teamName)`
    }) 
  }
}