我通过this
指针调用本地(类)函数,但得到错误'Uncaught TypeError: undefined is not a function'
。 Probem在线发生
this.createtimetable();
loadtimetable
函数{/ 1}}。
我的JS(相关)是:
this.createtimetable = function () {
this.inside_timetable = [];
for (var d = new Date(in_week_start); d <= new Date(in_week_end); d.setDate(d.getDate() + 1)) {
console.log(new Date(d));
daysOfYear.push(new Date(d));
}
}
this.loadtimetable = function (in_guide_id, in_week_start, in_week_end) {
this.guide_id = in_guide_id;
this.week_start = in_week_start;
this.week_end = in_week_end;
$.post("./j.php", {
guide_id : in_guide_id,
week_start : in_week_start,
week_end : in_week_end
})
.done(function (data) {
var res_arr = jQuery.parseJSON(data);
if (res_arr.code == 0) {
this.excursions_base = res_arr.answer;
alertify.success("Data extracted");
this.createtimetable();
} else {
alertify.error("Some problem occured." + data);
}
}).fail(function () {
alertify.alert("Error. Please, refresh page, or try later. We are sorry. Write or call us with your question!");
});
}
按名称调用(即createtimetable())也会失败。谢谢你的想法!
答案 0 :(得分:3)
您的代码在回调中执行,this
不再指向您的对象。您应该使用闭包,将this
别名化为self
,或明确绑定此
this.createtimetable = function () {
this.inside_timetable = [];
for (var d = new Date(in_week_start); d <= new Date(in_week_end); d.setDate(d.getDate() + 1)) {
console.log(new Date(d));
daysOfYear.push(new Date(d));
}
}
this.loadtimetable = function (in_guide_id, in_week_start, in_week_end) {
this.guide_id = in_guide_id;
this.week_start = in_week_start;
this.week_end = in_week_end;
$.post("./j.php", {
guide_id: in_guide_id,
week_start: in_week_start,
week_end: in_week_end
})
.done(function (data) {
var res_arr = jQuery.parseJSON(data);
if (res_arr.code == 0) {
this.excursions_base = res_arr.answer;
alertify.success("Data extracted");
this.createtimetable();
} else {
alertify.error("Some problem occured." + data);
}
}.bind(this)).fail(function () {
alertify.alert("Error. Please, refresh page, or try later. We are sorry. Write or call us with your question!");
}.bind(this));
}
答案 1 :(得分:2)
在帖子函数调用之外存储$(this)
的引用并在done
回调函数中使用它,此处this
不引用您的对象。
this.loadtimetable = function(in_guide_id, in_week_start, in_week_end)
{
var self = this; //store reference of this
$.post( "./j.php", {})
.done(function( data ) {
self.createtimetable(); //Here instead of this use your variable
});
}
如果您愿意使用$.ajax()
而不是$.post()
。您可以使用context选项。
此对象将成为所有与Ajax相关的回调的上下文。默认情况下,上下文是一个对象,表示调用中使用的ajax设置(
$.ajaxSettings
与传递给$.ajax
的设置合并)。 (...)
$.ajax({
context: this
});