【问题标题】:Property of a property doesn't have 'this' as a reference to the root object属性的属性没有“this”作为对根对象的引用
【发布时间】:2020-01-12 23:02:12
【问题描述】:

我创建了以下变量:

var orientations = {
    E: {R: this.S, L: this.N},
    W: {R: this.N, L: this.S},
    N: {R: this.E, L: this.W},
    S: {R: this.W, L: this.E},
}

我正在尝试引用我的 orientations 对象,但在我的代码中,“this”引用了窗口对象。我猜这可能是因为我深入到物体的两层。 有没有办法引用 orientations 对象本身?

【问题讨论】:

  • 这段代码是否在事件处理程序中,例如DOMContentLoaded?这可以解释为什么this === window

标签: javascript object this javascript-objects


【解决方案1】:

您的代码能够访问this的一种方式:

var obj = {
  E: {},
  W: {},
  N: {},
  S: {},
  
  initMyself: function() {
    Object.assign(this.E, {R: this.S, L: this.N});
    Object.assign(this.W, {R: this.N, L: this.S});
    Object.assign(this.N, {R: this.E, L: this.W});
    Object.assign(this.S, {R: this.W, L: this.E});
  }
};

obj.initMyself();

console.log(obj.E.R === obj.S);

简单的规则是,当您拥有obj.fn() 时,在fn() 的代码中,this 将绑定到obj。但是,如果您有g = obj.fn;,然后是g(),则g() 内部的代码将this 绑定到全局对象。

而且您的要求也可能有“自我”引用。您将 E.R 设置为引用 SS 尚不存在。所以这就是为什么我的代码首先创建它们,然后 Object.assign() 几乎只是将属性复制过来。

Object.assign(this.E, {R: this.S, L: this.N});

只是

this.E.R = this.S;
this.E.L = this.N;

您的代码可能的一种方式是:

var orientations = (function() {
  var obj = {
    E: {},
    W: {},
    N: {},
    S: {},

    initMyself: function() {
      Object.assign(this.E, {R: this.S, L: this.N});
      Object.assign(this.W, {R: this.N, L: this.S});
      Object.assign(this.N, {R: this.E, L: this.W});
      Object.assign(this.S, {R: this.W, L: this.E});
    }
  };

  obj.initMyself();
  delete obj.initMyself;

  return obj;
}());

console.log(orientations.E.R === orientations.S);

【讨论】:

    【解决方案2】:

    您想使用this 的方式无效。 this 只有在新的词法范围内才能以您想要的方式定义。看到这个问题Self-references in object literals / initializers

    【讨论】:

      【解决方案3】:

      我能做到的最好...(有更好的吗?)

      const orientations= { E: { RL: 'SN' } 
                          , W: { RL: 'NS' } 
                          , N: { RL: 'EW' } 
                          , S: { RL: 'WE' } 
                          } 
      
      for(let o in orientations) {
        orientations[o].R = orientations[ orientations[o].RL.charAt(0) ]
        orientations[o].L = orientations[ orientations[o].RL.charAt(1) ]
        delete orientations[o].RL  // no more needed
      }
      
      console.log( orientations.W.R === orientations.N  )

      【讨论】:

        猜你喜欢
        • 2012-12-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 1970-01-01
        • 2019-07-29
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        相关资源
        最近更新 更多