调用此$ http请求后(使用server.refresh();
)
MinecraftServer.prototype.refresh = function(){
return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);
}
此函数的
this
是window
对象,而不是MinecraftServer
对象:MinecraftServer.prototype.acceptData = function(data){
data = data.data
if(data && data.online){
this.online = data.online;
//do more stuff
} else { // do more stuff }
}
因此,
MinecraftServer
不会获取window
对象的属性更新,而是获取属性。万一这有帮助,这是我简短的工厂代码:
.factory('MinecraftServer',function($http){
function MinecraftServer(name, ip) { //does stuff }
MinecraftServer.prototype.acceptData = function(data){
data = data.data
if(data && data.online){
this.online = data.online;
//do more stuff
} else { // do more stuff }
}
MinecraftServer.prototype.refresh = function(){return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);}
MinecraftServer.build = function(name, ip){return new MinecraftServer(name, ip)};
return MinecraftServer;
})
最佳答案
this
作为回调正在使用其他this
。
使用.bind
:
return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData.bind(this));
关于javascript - JavaScript`this`语句不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32025620/