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

Gun*_*ter 6 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)
    }
  )
}
Run Code Online (Sandbox Code Playgroud)

这4个函数具有混合和匹配的函数语法.调用嵌套函数时,func:with arrow函数返回空白.

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

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

Bar*_*mar 5

当您定义a和时d,值this是顶级window对象,因为您不在某个其他对象的上下文中,并且这将保存在箭头函数中.window.name是一个空字符串,所以这就是你所看到的,当你调用a.func()d.func().

箭头函数通常不应该用作方法函数,因为它们无法访问它们所调用的对象.当你想保留this你创建它们的绑定时使用它们(就像其他闭包变量一样).

  • @GundamMeister - 换句话说,使用正确的工具 - 在MDN文档中,它声明*这些函数表达式最适合非方法函数* - 您的代码试图将它们用作方法函数 (3认同)

sim*_*mon 3

对于 A 情况,您实际上是将其保留到 window(如果在浏览器中运行),因此您返回的将是 window.name。

\n\n

然而,对于 D,它仍然返回空白,因为它是在“this”的函数级别上返回的。在您的情况下,由于您没有创建 D 的新实例,而是使用 d 作为功能对象本身,因此 this 也指向 window. (我将发布更多有关后者的信息,但现在,这是一个示例)。

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

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

\n\n
e = function(){\n  this.name = "Elizabeth2"\n  return(\n    {\n      name:"Elizabeth1",\n      func: function(){console.log(this.name)}\n    }\n  )\n}\ne().func();  // Elizabeth1\ne().name;    // Elizabeth1\ne()[\'name\']; // Elizabeth1\ne();         // {name: "Elizabeth1", func: \xc6\x92}\n
Run Code Online (Sandbox Code Playgroud)\n