-1

I'm having some trouble accessing variables within my object.

I'm getting returned undefined when I try to access the variables.

My code looks like this:

var app = {
  data: function() {
    this.labels = [1, 2, 3, 4, 5];
  },
  barChartData: {
    labels: this.labels, // this is undefined
    datasets: [{
        data: this.data1 // this is undefined
    }, {
        data: this.data2 // this is undefined
    }]
  },

  },
  init: function() {
    this.data();
  }
}
app.init();
  • `barChartData` is defined before the call of `data()`, just add `this.barChartData.labels = this.labels` at the end of the **init** function. `data1` and `data2` are not defined, so of course their values are undefined – Olivier Boissé Aug 19 '16 at 11:47
  • Possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – nils Aug 19 '16 at 12:32

2 Answers2

1

I found that you have a

  },

to much in your code. The working code is then:

var app = {
  data: function(){
    this.barChartData.labels = [1, 2, 3, 4, 5];
    this.barChartData.data1 = [1, 2, 3, 4, 5];
    this.barChartData.data2 = [1, 2, 3, 4, 5];
  },
  barChartData:{
      labels: [],
      datasets: [{
          data: []
      }, {
          data: []
      }]    
  },

  init: function() {
    this.data();
  }
}
app.init();
console.log(app.barChartData.labels);

Sorry for the first bad code. This one works and initializes the arrays.

0

Got it. Thanks oliv37 for pointing out that the order was wrong.

var app = {
  data: function() {
    this.labels = [1, 2, 3, 4, 5];
    this.data1 = [1, 2, 3, 4, 5];
    this.data2 = [1, 2, 3, 4, 5];
  },
  barChartData: function() {
    data = {
      labels: this.labels,
      datasets: [{
        data: this.data1
      }, {
        data: this.data2
      }] 
    }
  },
  init: function() {
    this.data();
    this.barChartData();
  }
}
app.init();