javascript this.function 不是函数错误,但函数存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9263694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
this.function is not a function error, but function exists
提问by Aine
I have some code to get calendar events and display them. The display is only updated if the events have changed, since the last call.
我有一些代码来获取日历事件并显示它们。仅当自上次调用以来事件发生更改时,才会更新显示。
var calendar = {
events = null,
display_calendar_events : function (data) {
// Some display stuff...
},
get_events: function() {
// Get messages for calendar
$.getJSON("/ajax/get-events/", function(json){
var new_events = json.data;
// If events haven't changed, do nothing
if (this.events === new_events) {
return true;
}
// Events have changed.
// Save new events
this.events = new_events;
// Display new events
this.display_calendar_events(json);
});
},
}
I call this with:
我称之为:
calendar.get_queued_events();
The problem is, I'm getting the error "this.display_calendar_events is not a function"(last line of code). But if I change this line to:
问题是,我收到错误“this.display_calendar_events 不是函数”(最后一行代码)。但是,如果我将此行更改为:
calendar.display_canendar_events(josn)
it works. The storing of the old events with "this.events" works fine in both cases.
有用。在这两种情况下,使用“this.events”存储旧事件都可以正常工作。
Can someone explain this to me? How can "this" work for some stuff and not others? Thanks.
谁可以给我解释一下这个?“这个”如何适用于某些东西而不适用于其他东西?谢谢。
回答by Ryan P
In a jQuery AJAX callback, this
references the ajax request object. Try using var self = this;
before your AJAX call, and in the callback use self.display_calendar_events()
.
在 jQuery AJAX 回调中,this
引用 ajax 请求对象。尝试var self = this;
在 AJAX 调用之前使用,并在回调中使用self.display_calendar_events()
.
Alternatively, you could just reference calendar.display_calendar_events()
directly. But that's not easily refactored like the self
method is.
或者,您可以直接引用calendar.display_calendar_events()
。但这不像self
方法那样容易重构。
回答by andreapier
When you call this.display_calendar_events() inside the ajax request you area ctually in a different context than your object. You have to do:
当您在 ajax 请求中调用 this.display_calendar_events() 时,您实际上处于与对象不同的上下文中。你必须做:
var calendar = {
events = null,
display_calendar_events : function (data) {
// Some display stuff...
},
get_events: function() {
var $this = this;
// Get messages for calendar
$.getJSON("/ajax/get-events/", function(json){
var new_events = json.data;
// If events haven't changed, do nothing
if ($this.events === new_events) {
return true;
}
// Events have changed.
// Save new events
$this.events = new_events;
// Display new events
$this.display_calendar_events(json);
});
},
}