有没有办法为一个jQuery的ajax成功函数来访问它包含的对象吗?没有办法、函数、对象、来访问

2023-09-10 14:21:07 作者:ζ   懂我再爱我°

我的JavaScript是这样的:

I have javascript like this:

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?

推荐答案

您正在寻找的上下文参数添加到 AJAX 方法。 它允许你设置的所有回调将被称为上下文。

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.

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