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

查看:17
本文介绍了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)
    }
  )
}

这4个函数有mix &匹配的函数语法.调用嵌套函数时,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()//返回查理"
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 用作功能对象本身,因此这也指向 window.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天全站免登陆