2013-06-18 118 views
0

我在javascript中声明了一个对象方法。 这个方法里面我想做一个ajax调用,当调用完成时,修改这个对象的一些属性。在另一个对象内部传递对象引用

Bubble.prototype.draw = function(){ 

console.log(this.attribute) // -> works fine 

var req = $.ajax({ 
url: "someFile.php", 
type: "post", 
data: someData 
}); 

// handle response 
req.done(function (response, textStatus, jqXHR){ 

console.log(this.attribute) // -> not in the scope, obviously 

}); 

} 

我怎样才能把this.attributereq.done范围有多大?如何访问req.done内部的整个Bubble对象?目前,所有我Bubble S的是一个数组,所以我可以只通过在这个数组的索引和访问属性这样(array[i].attribute)。我想有一个更好的方法来做到这一点。

+0

你试过背景:这一点,因为阿贾克斯的选择吗?不知道它的工作原理在这种情况下 –

+1

'this'需要保存在某个地方'$。阿贾克斯()'函数外部的变量。 'var self = this;'那么你可以使用'self'来访问'this'。 –

回答

1

看起来它是这样工作的,这似乎是这样做的土办法,使用上下文选项:

Bubble.prototype.draw = function() { 

    console.log(this.attribute) // -> works fine 

    var req = $.ajax({ 
     url: "someFile.php", 
     type: "post", 
     data: someData, 
     context: this 
    }); 

    // handle response 
    req.done(function (response, textStatus, jqXHR) { 

     console.log(this.attribute); 

    }); 

} 
+0

这是最好的解决方案,接受。谢谢! – Saturnix

3
Bubble.prototype.draw = function() { 
    console.log(this.attribute) // -> works fine 
    var req = $.ajax({ 
     url: "someFile.php", 
     type: "post", 
     data: someData 
    }), 
     self = this; //save this object 
    // handle response 
    req.done(function (response, textStatus, jqXHR) { 
     console.log(self.attribute) //access parent this 
    }); 
} 
+0

工作正常,谢谢! – Saturnix

3

这是因为,当Ajax回调被称为执行上下文是不同的,这意味着该回调方法点内的this关键字到另一个对象,而不是所期望的气泡对象。

有如下图所示

使用$ .proxy到自定义执行上下文传递给回调处理

Bubble.prototype.draw = function(){ 

    console.log(this.attribute) // -> works fine 

    var req = $.ajax({ 
     url: "someFile.php", 
     type: "post", 
     data: someData 
    }); 

    // handle response 
    req.done($.proxy(function (response, textStatus, jqXHR){ 

     console.log(this.attribute) // -> not in the scope, obviously 

    }, this)); 

} 

或者使用闭包变量这两种解决方案

Bubble.prototype.draw = function(){ 

    console.log(this.attribute) // -> works fine 

    var req = $.ajax({ 
     url: "someFile.php", 
     type: "post", 
     data: someData 
    }); 

    var _this = this; 
    // handle response 
    req.done(function (response, textStatus, jqXHR){ 

     console.log(_this .attribute) // -> not in the scope, obviously 

    }); 

} 
1

只需将this.attribute变量复制到另一个像这样的范围变量。

Bubble.prototype.draw = function(){ 

console.log(this.attribute) // -> works fine 
_this = this.attribute; 
var req = $.ajax({ 
url: "someFile.php", 
type: "post", 
data: someData 
}); 

// handle response 
req.done(function (response, textStatus, jqXHR){ 

console.log(_this) // -> not in the scope, obviously 

}); 

} 
+1

您在全局范围内设置_this,这里不是最好的方法 –