3

假设我有以下内容:

var object = {
    myfunc: function() {
        $.ajax({
           url: url,
           format: format,
           success: function() {

           console.log(this) // This refers to the ajax call and not "object"

                $.ajax({
                  url: url,
                  format: format,
                  success: function() {
                    console.log(this) // this refers to nested ajax call and not "object"
                  }
                });


           }
        });
    }
}

如何让“this”引用“object”而不是ajax调用?

4

4 回答 4

5

使用$.proxy()将自定义上下文传递给回调函数

var object = {
    myvar : "hello",
    myfunc : function() {
        $.ajax({
            url : url,
            format : format,
            success : $.proxy(function() {

                console.log(this) // This refers to the ajax
                // call and
                // not "object"

                $.ajax({
                    url : url,
                    format : format,
                    success : function() {
                        console.log(this) // this
                        // refers to
                        // nested ajax call
                        // and not "object"
                    }
                });

            }, this)
        });
    }
}
于 2013-04-25T13:26:37.407 回答
3

this当您仍在this保存所需值的上下文中时,将 的值复制到另一个变量。

var object = {
    myfunc: function() {
        var myObject = this;
        $.ajax({

然后使用该变量(它将在其中声明的函数的范围内,除非它们用另一个同名变量对其进行掩码)。

success: function() {
    console.log(myObject);
}
于 2013-04-25T13:27:47.100 回答
2

在我看来,这是一种比另一种更容易的方法。只需将引用存储在局部变量中并使用它而不是this.

var object = {
    var thisReference = this;
    myfunc: function() {
        $.ajax({
           url: url,
           format: format,
           success: function() {

           console.log(thisReference ) 

                $.ajax({
                  url: url,
                  format: format,
                  success: function() {
                    console.log(thisReference ) 
                  }
                });


           }
        });
    }
}
于 2013-04-25T13:28:28.187 回答
0

使对象成为构造函数。

/*
  constructors start with capital letters, by convention.  
  Javascript already has an 'Object' constructor, so we'll change the name.
*/
var MyObject = function(){
  // 'this' now refers to the object.  
  // We'll save a reference to it for use within functions
  var me = this;

  this.myvar: "hello";
  this.myfunc: function(){
    // do whatever you want.  Use 'me' to access your object.
    console.log(me);  // the object!
  }
}

你使用它的方式可能会改变,这取决于你是否想假装是面向对象的。就是这样:

var obj = new MyObject();  //make the object
obj.myfunc();            //call your function
于 2013-04-25T13:36:08.563 回答