Search code examples
javascriptfunction-prototypes

Javascript: Object has no method when using prototypes


Why do I have to call new Chart() to fire a method from the same class(per say)? Is this the correct way to do this? Thanks.

  function Chart(location, startDateString, endDateString) {  

    this.location = location;
    this.startDateString = startDateString;
    this.endDateString = endDateString;
}


Chart.prototype.fnDrawStaticChart = function(chartUrl, chartData) {

    $.get(chartUrl, function() {                       
        $('#'+chartData.wrapSpecId).attr('src', chartUrl);                             
    });      
}

Chart.prototype.fnDraw = function(fnStaticChartJSON, fnStaticChartImage) {        

    $.getJSON(fnStaticChartJSON, function(data) { 

        if (data.chartData.length > 0) {    

            $('#chartDiv').append($('#template').jqote(data, '@'));       

            $.each(data.chartData, function(index, chartData) { 

                var pkgLineId = chartData.wrapSpec2.pkgLineId.pkgLineId;             
                var wrapSpecId = chartData.wrapSpecId;
                var startDate = data.startDate;
                var endDate = data.endDate;

                var chartUrl = fnStaticChartImage({
                    pkg_line_id: pkgLineId, 
                    wrap_spec_id: wrapSpecId, 
                    start_date: startDate, 
                    end_date: endDate
                });

                this.fnDrawStaticChart(chartUrl, chartData); //can't do this.  
                new Chart().fnDrawStaticChart(chartUrl, chartData); CAN do this.



            });      
    }); 
}

Solution

  • It's a simple scoping issue. this points to the function you passed to $.each. You have to store the old this reference in another variable:

    Chart.prototype.fnDraw = function(fnStaticChartJSON, fnStaticChartImage) {        
        var self = this;
        $.getJSON(fnStaticChartJSON, function(data) { 
    
            if (data.chartData.length > 0) {    
    
                $('#chartDiv').append($('#template').jqote(data, '@'));       
    
                $.each(data.chartData, function(index, chartData) { 
    
                    var pkgLineId = chartData.wrapSpec2.pkgLineId.pkgLineId;             
                    var wrapSpecId = chartData.wrapSpecId;
                    var startDate = data.startDate;
                    var endDate = data.endDate;
    
                    var chartUrl = fnStaticChartImage({
                        pkg_line_id: pkgLineId, 
                        wrap_spec_id: wrapSpecId, 
                        start_date: startDate, 
                        end_date: endDate
                    });
    
                    self.fnDrawStaticChart(chartUrl, chartData);
                    new Chart().fnDrawStaticChart(chartUrl, chartData);
                });      
        }); 
    }