In your code, "this" is pretty much always referring to the myChat object.
If you were to call init you would write myChat.init()
. init is part of the myChat object, so this
refers to the containing object. Init is specified within the scope of myChat, as are all of your other functions, meaning that this function and all others are part of myChat
, and therefore this
is myChat
var myChat = {
init: function () {
this.fetchInitialData();
this.bindSendEvent();
this.refresh();
},
...
}
Also, if you look at the jquery documentation on extend (http://api.jquery.com/jQuery.extend/), the description is "Merge the contents of two or more objects together into the first object.". So when you $.extend(myChat, coreChat);
, what you're actually doing is copying all properties from coreChat
into the myChat
object. So, when you call fetch in this code, you're actually calling the fetch method that has been copied into your myChat
object, so this
also still refers to myChat
. To further reinforce that these methods were added to the myChat object, notice you're calling myChat.display
? That was defined in coreChat
, but you're accessing it using myChat
instead.
updateMessages: function () {
this.fetch(function (messages) {
myChat.display(messages);
});
}
There is an instance where this
does not refer to myChat
. That is in the display function of coreChat
. Since you're using the jquery .each function, within the scope of that function, this
refers to the list item that the function is being run on, and NOT the coreChat
object (or more precisely the myChat
copy of this coreChat
function as explained above).
var messageNode = $(".messages").find("li");
messageNode.each(function (i) {
var $this = $(this);
if ($this.text() !== messages[i]) {
$this.text(messages[i]);
}
});
As for part 2 of your question:
The function that is passed as a parameter to fetch
is a callback function for when fetch
is completed. The definition for fetch
includes a function as a parameter:
fetch: function (fn) {
In the .done
function, the callback function is invoked, passing in the message data, and returning the result of that callback:
return fn(messages);
So, you call .fetch
and pass in your function, fetch
executes and does all of its processing, and then fetch
calls your passed-in function.