找到你要的答案

Q:Javascript `this` statement not working

Q:JavaScript `这`声明不工作

After calling this $http request (with server.refresh();)

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

This function's this is the window object, instead of the MinecraftServer object:

MinecraftServer.prototype.acceptData = function(data){
    data = data.data

    if(data && data.online){
        this.online = data.online;
        //do more stuff       
    } else { // do more stuff }
}

So instead of the MinecraftServer object getting it's attributes updated, the window gets the attributes.

In case this will help, here is my abriged factory code:

.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;
})

调用此为HTTP请求后(与服务器。refresh();)

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

这个函数是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对象得到的属性更新窗口获得属性。

如果这会有帮助,这是我的简略工厂代码:

.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;
})
answer1: 回答1:

this as a callback is using some other this.

Use .bind:

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

这作为一个回调是使用其他一些。

使用绑定:

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