使用功能设置对象成员失败 [英] Setting members of object using function fails
问题描述
我正在尝试对我正在创建的游戏实施一种多人游戏扩展.在XMLHttpRequest之后,将返回游戏ID,即多人游戏会话的ID.
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.
我正在使用以下代码,其中Multiplayer是静态类:
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);
});
}
}
失败,因为似乎无法使用this.gameID = parseInt(text)
.当我将其更改为Multiplayer.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.
this.gameID
似乎是未定义的,而Multiplayer.gameID
可以被读写.
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没有类,并且this
的行为与您期望的来自C ++或Java背景无关.尝试将您的创建函数更改为此:
Javascript doesn't have classes, and this
does not behave as you expect coming from a C++ or Java background. Try changing your create function to this:
function() {
var that = this;
$.get(this.baseURL, {'a':'c'}, function(text) {
that.gameID = parseInt(text);
});
}
关键点在于,每个function()都使用特定的this
值调用,并且它可能与封闭函数的值不同.
The key points are that every function() is invoked with a particular this
value, and it may not be the same value as the enclosing function's.
这篇关于使用功能设置对象成员失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!