I’m trying to implement a kind of multiplayer extension to a game I’m creating. After a XMLHttpRequest, a game ID is returned, i.e. the ID of a multiplayer session.
I’m using the following code, in which Multiplayer is a static class:
var Multiplayer = {
baseURL: 'http://127.0.0.1:8888/m',
gameID: -1,
create:
function() {
$.get(this.baseURL, {'a':'c'}, function(text) {
this.gameID = parseInt(text);
});
}
}
It fails, because it seems this.gameID = parseInt(text) cannot be used. When I change it to Multiplayer.gameID = parseInt(text), it works like a charm.
It seems like this.gameID is undefined, while Multiplayer.gameID can both be written to and read from.
Is this correct and if so, why is this the case?
Javascript doesn’t have classes, and
thisdoes not behave as you expect coming from a C++ or Java background. Try changing your create function to this:The key points are that every function() is invoked with a particular
thisvalue, and it may not be the same value as the enclosing function’s.