0

In the below example, how can i access enums.ROCK inside the prop? As it currently stand, i get an error Uncaught TypeError: Cannot read property 'enums' of undefined. Plz check comment ERROR LINE.

const app = {
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, take note of this keyword
  },
  prop: {
    isGameRunning: false,
    mySelection: this.app.enums.ROCK //ERROR LINE
  }
};

I have tried it with mySelection: app.enums.ROCK as well and in this case i get Uncaught ReferenceError: Cannot access 'app' before initialization.

Sample 1: https://jsfiddle.net/5zp7yode/

Sample 2: https://jsfiddle.net/5zp7yode/1/

Where as the following works without any issues:

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

alert(person.fullName());

Sample 3: https://jsfiddle.net/0o93afLq/

I have also tried with following but still can't access enums inside prop:

const app = {
  self: this,
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, take note of this keyword
  },
  prop: {
    isGameRunning: false,
    mySelection: self.enums.ROCK
  }
};

alert(app.prop.mySelection);

Sample 4: https://jsfiddle.net/x89kj2zn/

and another one working with function but i can't call the function inside the prop:

const app = {
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    DEFAULT_USER_CHOICE: this.ROCK //default, take note of this keyword
  },
  prop: {
    isGameRunning: false
  },
  getMySelection: function(){
    return app.enums.ROCK;
  }
};
alert(app.getMySelection());

Sample 5: https://jsfiddle.net/v5qzdx3s/

Nathaniel Flick
  • 2,504
  • 2
  • 17
  • 25
learning...
  • 2,759
  • 6
  • 51
  • 84
  • 2
    "how can i access enums.ROCK inside the prop?" --- you cannot, it does not exist yet. – zerkms Dec 03 '19 at 04:04
  • 1
    Please go through [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429) and [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202) – adiga Dec 03 '19 at 04:06
  • Hmmm so `getters` will work and `Function Hoisting` will work, does this seems correct statement? – learning... Dec 03 '19 at 04:11

1 Answers1

1

You can make use of get.

const app = {
  enums: {
    ROCK: 'ROCK',
    PAPER: 'PAPER',
    SCISSORS: 'SCISSORS',
    get DEFAULT_USER_CHOICE(){
      return app.enums.ROCK
    }
  },
  prop: {
    isGameRunning: false,
    get mySelection(){
      return app.enums.ROCK
    }
  }
};

console.log(app)
whitehat
  • 2,644
  • 1
  • 12
  • 35