ES6箭头函数和函数内的词法范围 [英] ES6 arrow function and lexical scope inside a function

查看:123
本文介绍了ES6箭头函数和函数内的词法范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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函数返回空格。

These 4 functions have mix & matched function syntax. When calling the nested function, the func: with arrow function returns blanks.

a()。func()//返回空白

b()。func()//返回Brian

c()。func()//返回Charlie

d()。func()//返回空白

我认为箭头功能保留了this的范围?这种行为似乎与我的想法相反。箭头函数什么时候超出范围?

I thought the arrow function retain the scope of "this"? The behavior seems to be the opposite of what I've thought. When did the arrow function went out of scope?

推荐答案

对于A案例,你实际上是一直保留这一点窗口(如果在浏览器中运行),所以它将是你要返回的window.name。

For the A case, you literally are preserving this all the way back to window (if ran in a browser), so it would be window.name that you are returning.

然而,对于D,它仍然是空白,因为它已经打开正在返回的this的功能级别。在您的情况下,由于您没有创建D的新实例,而是使用d作为功能对象本身,因此这也指向窗口。 (我会发布更多关于后者的内容,但是现在,这是一个例子)。

As for D however, it was returning blank still because it was on the function level of "this" that was returning. In your case, since you aren't creating a new instance of D but using d as a functional object itself, this points also to window. (I'll post more about the later, but for now, here is an example).

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绑定时的差异匿名函数而不是匿名箭头函数。

now to show difference if func is bound to anonymous function rather than anonymous arrow function.

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: ƒ}

这篇关于ES6箭头函数和函数内的词法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆