JavaScript上下文(this)

问题描述 投票:0回答:1

我在理解JS中的上下文时遇到问题。

i = 2

let obj = {
  i: 3,
  b: function() {
    let i = 4;
    let x = () => console.log(this.i);
    x()
  },
  c: function() {
    let i = 5;

    function y() {
      console.log(this.i);
    }
    y()
  },
};

let b = () => console.log(this.i)
let c = function() {
  console.log(this.i)
}

obj.b(); // 3
obj.c(); // 2
b(); // undefined
c(); // 2

根据MDN Web文档“在箭头功能中,this保留了封闭词法上下文的this的值。在全局代码中,它将设置为全局对象”。如果是这样,为什么b()不像c()一样打印i(= 2)?另外,当obj.c()位于obj{}对象内部时,为什么会打印2?

编辑:这是输出,我正在使用节点。有人可以帮我什么问题吗? :)

“截图”

javascript node.js this arrow-functions
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.