简体   繁体   中英

Sharing variable between functions

I'm having hard time trying to share a variable between javascript functions.

I basically have an object with 3 functions: one to fetch the data, one to render a chart and the third one to manipulate the chart itself.

My code looks like

 this.ChartManager = {
      plotChart: function(chartName) {
       ...
       ChartManager.createChart(seriesOptions);
      },

    createChart: function(seriesOptions) {
      var chart = $('#container').highcharts('StockChart', {
       ...
      });
    },

    toggleSeries: function(n) {
      current_series = chart.series[n];
      ...
    }
 };

But when in ToggleSeries I try to access the chart variable I get an 'undefined' error message.

How can I make the chart variable accessible from ToggleSeries?

Thanks for your help and have a nice day.

UPDATE - My working code is

this.ChartManager = {
      plotChart: function(chartName) {
       ...
       ChartManager.createChart(seriesOptions);
      },

    createChart: function(seriesOptions) {
       $('#container').highcharts('StockChart', {
       ...
      });
    },

    toggleSeries: function(n) {
    var current_series = $('#container').highcharts().series[n];
      ...
    }
 };

Define variables in the object, and use them in any member function.

 this.ChartManager = {
    globalVar1:0,
    chart:0,
    plotChart: function(chartName) {
       ...
       ChartManager.createChart(seriesOptions);
      },

    createChart: function(seriesOptions) {
      this.chart = $('#container').highcharts('StockChart', {
       ...
      });
    },

    toggleSeries: function(n) {
      current_series = this.chart.series[n];
      ...
    }
 };

You can't - a variable defined inside of a function stays inside that function's scope. You'd have to move that variable either into the global scope or attach it to an object accessible from the current scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM