嵌套对象文字中"this"的词汇上下文 [英] Lexical context of 'this' in Nested Object Literals

查看:44
本文介绍了嵌套对象文字中"this"的词汇上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之所以问,是因为我已经阅读了与此问题类似(但不相等)的问题.

据我了解,我明白为什么此代码有效:

 let myObj = {
  name: 'inner text',
  myFunction: () => {
    console.log("before text " + this.name + " after text");
  }
}
myObj.myFunction(); 

原因:创建箭头函数(myObj)的上下文属于全局范围(取决于严格模式等,它是windowundefined)./p>

我明白了.但是在嵌套对象常量的情况下,难道不是外部对象常量是arrow函数的继承上下文吗?

 let outer = {
  name: 'outer',
  obj: {
    name: 'inner',
    myFunction: () => {
      console.log("before text " + this.name + " after text");
    }
  }
}
outer.obj.myFunction(); 

我希望this引用outer的上下文,这是obj嵌套的对象文字. 事实并非如此,也是我无法正确理解这种继承的词汇范围的原因.

有人能解释为什么会这样吗?

解决方案

但是在嵌套对象文字的情况下,不应该将外部对象文字作为箭头函数的继承上下文,如以下示例所示?

否.

箭头功能复制this当前值;

var object = {
     a: this,
     b: { 
         a: this,
         b: {
             a: this
         }
     } 
}

嵌套多少级都没有关系,this的值不变.

由于对象文字的每个级别都出现在相同的函数中,因此它们都具有相同的this值.

I'm asking because I've read similar (but not equal) questions about this issue.

As far as I understand, I get why this code would NOT work:

let myObj = {
  name: 'inner text',
  myFunction: () => {
    console.log("before text " + this.name + " after text");
  }
}
myObj.myFunction();

Reason: the context where the arrow function is created (myObj) belongs to the global scope (which is window or undefined depending on strict mode and so on).

I get that. But in the case of nested object literals, shouldn't be the outer object literal the inherited context for the arrow function like following example?

let outer = {
  name: 'outer',
  obj: {
    name: 'inner',
    myFunction: () => {
      console.log("before text " + this.name + " after text");
    }
  }
}
outer.obj.myFunction();

I would expect that this refers to the context of outer, which is the object literal where obj is nested.
This is not the case and the reason I don't understand properly this inherited lexical scope.

Could someone throw some light about why is that happening?

解决方案

But in the case of nested object literals, shouldn't be the outer object literal the inherited context for the arrow function like following example?

No.

An arrow function copies the current value of this;

var object = {
     a: this,
     b: { 
         a: this,
         b: {
             a: this
         }
     } 
}

It doesn't matter how many levels you nest it, the value of this doesn't change.

Since every level of the object literal appears in the same function, they all get the same this value.

这篇关于嵌套对象文字中"this"的词汇上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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