有没有办法让JQuery ajax成功函数访问它所包含的对象?

时间:2021-09-25 19:58:05

I have javascript like this:

我有这样的javascript:

function Cat() { 

  this.meow = function() { // meow };

  $.ajax( do AJAX call, success: this.meow(); );

}

var TopCat = new Cat();

This does not work because 'this' makes no sense in the context of the success function. Is there an elegant solution?

这不起作用,因为'this'在成功函数的上下文中没有意义。有优雅的解决方案吗?

1 个解决方案

#1


7  

You're looking for the context parameter to the ajax method.
It allows you to set the context in which all callbacks will be called.

您正在寻找ajax方法的context参数。它允许您设置将调用所有回调的上下文。

function Cat() { 
    this.meow = function() { // meow };
    $.ajax({
        context: this, 
        success: function() { this.meow(); } 
    });    
}

#1


7  

You're looking for the context parameter to the ajax method.
It allows you to set the context in which all callbacks will be called.

您正在寻找ajax方法的context参数。它允许您设置将调用所有回调的上下文。

function Cat() { 
    this.meow = function() { // meow };
    $.ajax({
        context: this, 
        success: function() { this.meow(); } 
    });    
}