【问题标题】:Javascript `this` statement not workingJavascript`this`语句不起作用
【发布时间】:2015-08-15 14:17:59
【问题描述】:

调用此 $http 请求后(使用server.refresh();

MinecraftServer.prototype.refresh = function(){
    return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData);
}

这个函数的thiswindow对象,而不是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;
})

【问题讨论】:

  • 您可能想了解更多关于how this works in JavaScript 的信息。它肯定会帮助您更好地理解。
  • @fstanis - 非常感谢!这对我有很大帮助。

标签: javascript angularjs factory angularjs-factory


【解决方案1】:

this 作为回调正在使用其他一些this

使用.bind:

return $http.get("http://mcping.net/api/" + this.ip).then(this.acceptData.bind(this));

【讨论】:

  • 这似乎可行!谢谢。 (我也会尽快接受)
  • @charlietfl 你必须绑定到你要修改的函数this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
  • 2012-11-30
  • 2015-03-28
相关资源
最近更新 更多