0

I created the following variable:

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},
}

I'm trying to reference my orientations object but in my code 'this' reference the window object. I'm guessing that it might be because I'm two level deep into the object. Is there any way to reference the orientations object itself?

Joe
  • 443
  • 1
  • 4
  • 21
  • Is this code inside an event-handler, such as `DOMContentLoaded`? That would explain why `this === window`. – Dai Jan 12 '20 at 23:05

3 Answers3

0

The way you want to use this isn't valid. this would only be defined in the way you want if it was in a new lexical scope. See this question Self-references in object literals / initializers

Connor Burton
  • 419
  • 1
  • 5
  • 15
0

the best I can do... (is there better ?)

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  )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

One way for your code to be able to access 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);

The simple rule is, when you have obj.fn(), then inside of fn()'s code, the this is bound to obj. But if you have g = obj.fn; and then g(), the code inside of g() will have this bound to the global object.

And your requirement also may have the "self" references. You are setting E.R to refer to S but S doesn't exist yet. So that's why my code created them first, and then the Object.assign() pretty much just copy the properties over.

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

is just

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

One way your code could have been is:

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);
nonopolarity
  • 146,324
  • 131
  • 460
  • 740