ES6箭头函数和函数内的词法范围

时间:2018-01-23 22:10:26

标签: javascript ecmascript-6

let a = () => (
  {
    name:"Anna",
    func: () => console.log(this.name)
  }
)

let b = () => (
  {
    name:"Brian",
    func: function(){ console.log(this.name) }
  }
)

let c = function(){
  return(
    {
      name:"Charlie",
      func: function(){ console.log(this.name) }
    }
  )
}

let d = function(){
  return(
    {
      name:"Denny",
      func: () => console.log(this.name)
    }
  )
}

这四个功能混合使用匹配的函数语法。当调用嵌套函数时,func:with arrow函数返回空格。

a().func() // returns blank
b().func() // returns "Brian"
c().func() // returns "Charlie"
d().func() // returns blank

我认为箭头功能保留了“这个”的范围?这种行为似乎与我的想法相反。箭头功能何时超出范围?

2 个答案:

答案 0 :(得分:5)

当您定义ad时,this的值是顶级window对象,因为您不在某些对象的上下文中其他对象,这将保存在箭头函数中。 window.name是一个空字符串,因此当您致电a.func()d.func()时,您会看到这一点。

箭头函数通常不应用作方法函数,因为它们无法访问它们所调用的对象。如果要保留this与创建它们的绑定(就像其他闭包变量一样),请使用它们。

答案 1 :(得分:2)

对于A案例,你确实将这一直保留在窗口中(如果在浏览器中运行),那么你将返回window.name。

然而,对于D来说,它仍然是空白,因为它处于"这个"的功能级别。那是回来了。在您的情况下,由于您不是创建D的新实例但是使用d作为功能对象本身,这也指向窗口。 (我将更多地介绍后者,但是现在,这是一个例子)。

let e = function(){
  this.name = "Elizabeth2"  //this is on the functional level
  return(
    {
      name:"Elizabeth1",
      func: () => console.log(this.name)
    }
  )
}
e().func();       // Elizabeth2 
                  // even though it is on the functional level, the way you're calling it here makes this.name == window.name;
let ee = new e(); // however, imagine if you did this kind of a call instead
ee.func();        // Elizabeth2
                  // this is also on the functional level, HOWEVER, it is not binding this.name to window.name
ee.name;          // Elizabeth1
e().name;         // Elizabeth1
e()['name'];      // Elizabeth1
e();              // {name: "Elizabeth1", func: ƒ}

现在显示func是否绑定到匿名函数而不是匿名箭头函数。

e = function(){
  this.name = "Elizabeth2"
  return(
    {
      name:"Elizabeth1",
      func: function(){console.log(this.name)}
    }
  )
}
e().func();  // Elizabeth1
e().name;    // Elizabeth1
e()['name']; // Elizabeth1
e();         // {name: "Elizabeth1", func: ƒ}