0

I am trying to learn JavaScript and came to a dead end. Version ES5.

var person = {
  cars: ["Ford", "Mercedes", "S Coupe"],
  garages: { 1: this.cars },
};

    console.log(person); 
//outputs 
//    {
//      cars: [ 'Ford', 'Mercedes', 'S Coupe' ],
//      garages: { '1': undefined }
//    }

Why is garages["1"] undefined? is it because cars is not initialized?

ati
  • 45
  • 2
  • 3
    *is it because cars is not initialized?* - The object doesn't exist yet so `this` refers to something else – Konrad Dec 26 '22 at 19:23

2 Answers2

0

If you really want the same object to be referenced twice in obj you could do the following:

const obj=(cars=>(
 {person:{cars,garages:{1:cars}}})
)(["Ford", "Mercedes", "S Coupe"]);

console.log(JSON.stringify(obj));
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
-1

In addition, the this in that aspect is seeing the global this.

One way to go around that is to do something like

var person = {
  cars: ["Ford", "Mercedes", "S Coupe"],
  garages: { 1: person['cars'] },
};
Ahmad Khidir
  • 140
  • 1
  • 9