Why is my JavaScript code giving giving a reference error when I have defined the property inside the object?



I’m a beginner to javascript and learning about objects. When I run the initializeDeck method I get a reference error saying values/suits is not defined. However, I think I’m using the this keyword appropriately to access the objects properties. It would be immensely helpful if someone could explain this to me.

const myDeck = {
  deck : [],
  suits : ["hearts", "diamonds", "spades", "clubs"],
  values : "2,3,4,5,6,7,8,9,10,J,Q,K,A",
  
  initializeDeck : function() {
    this.values = values;
    this.suits = suits;
}}
console.log(myDeck.initializeDeck());

Answer

Your problem is not this.values. It is values. this.values can be accessed inside the method. this means the object myDeck here.

Even if you do:

const myDeck = {
  deck : [],
  suits : ["hearts", "diamonds", "spades", "clubs"],
  values : "2,3,4,5,6,7,8,9,10,J,Q,K,A",
  initializeDeck : function() {
    this.values = values;
    this.suits = suits;
}
}
console.log(values); //You will get an error here. values is not defined.

By the way you need not initialize. You are not using a constructor and this is a simple object literal. You can simply use myDeck.values outside.



Source: stackoverflow