Javascript jQuery-获取对此的引用
Javascript jQuery-获取对此的引用,javascript,jquery,Javascript,Jquery,这不是指同一件事 这不是指同一件事 尝试以下操作: function Request(params) { // Stuff stuff stuff // And then $.ajax( { type: 'GET', url: 'someurl', success: this.done }); } Request.prototype.done = function() { // "this" i
这
不是指同一件事 这
不是指同一件事 尝试以下操作:
function Request(params)
{
// Stuff stuff stuff
// And then
$.ajax(
{
type: 'GET',
url: 'someurl',
success: this.done
});
}
Request.prototype.done = function()
{
// "this" in this context will not refer to the Request instance.
// How to reach it?
}
请尝试以下操作:
function Request(params)
{
// Stuff stuff stuff
// And then
$.ajax(
{
type: 'GET',
url: 'someurl',
success: this.done
});
}
Request.prototype.done = function()
{
// "this" in this context will not refer to the Request instance.
// How to reach it?
}
您可以先捕获“这个”:
您可以先捕获“这个”:
显然,您可以将“context”参数添加到ajax请求中,如下所示:
function Request(params)
{
// Stuff stuff stuff
// And then
var $this = this;
$.ajax(
{
type: 'GET',
url: 'someurl',
success: function() { $this.done(); }
});
}
显然,您可以将“context”参数添加到ajax请求中,如下所示:
function Request(params)
{
// Stuff stuff stuff
// And then
var $this = this;
$.ajax(
{
type: 'GET',
url: 'someurl',
success: function() { $this.done(); }
});
}
“that”是本地的请求函数。是的,我在同一个“闭包”中使用“that”技巧,以避免失去对它的引用;我也试过了,但它不适用于原型设计。如果不使用prototype:)定义done,那么它就可以工作。它只适用于内联函数(使用闭包)。无论是否使用原型,函数请求(params){var that=this;this.done=function(){that…}….$.ajax({type:'GET',url:'someurl',success:this.done})都没有任何区别。这就是我对闭包的意思。“that”是请求函数的本地名称。是的,我使用的是“that”在同一个“闭包”中使用技巧,以避免丢失对此的引用;也尝试过它。它与原型不起作用。如果完成,它将起作用,而不是使用prototype:)。它仅适用于内联函数(使用闭包)。使用原型与否不会产生任何差异函数请求(参数){var that=this;this.done=function(){that…}..$.ajax({type:'GET',url:'someurl',success:this.done});这就是我对闭包的意思。为此,需要一个“上下文”参数可以添加到ajax请求中,引用此。但是,您的解决方案更通用,因此我将其设置为正确答案。为此,可以向ajax请求中添加一个“上下文”参数,引用此参数。但是,您的解决方案更通用,因此我将其设置为正确答案。
$.ajax(
{
type: 'GET',
url: 'someurl',
success: this.done,
context: this
});