gpt4 book ai didi

Javascript:对象在使用原型(prototype)时没有方法

转载 作者:行者123 更新时间:2023-11-30 18:41:38 24 4
gpt4 key购买 nike

为什么我必须调用 new Chart() 来触发来自同一个类的方法(比如)?这是正确的方法吗?谢谢。

  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.



});
});
}

最佳答案

这是一个简单的范围界定问题。 this 指向您传递给 $.each 的函数。您必须将旧的 this 引用存储在另一个变量中:

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);
});
});
}

关于Javascript:对象在使用原型(prototype)时没有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com