如何正确引用“这个”?

时间:2013-04-25 13:24:45

标签: javascript jquery

假设我有以下内容:

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 个答案:

答案 0 :(得分: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)
        });
    }
}

答案 1 :(得分:3)

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

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

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

success: function() {
    console.log(myObject);
}

答案 2 :(得分: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 ) 
                  }
                });


           }
        });
    }
}

答案 3 :(得分: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