2013-04-25 34 views
3

假設我有以下幾點:如何正確引用「this」?

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" 
        } 
       }); 


      } 
     }); 
    } 
} 

如何得到「這個」引用「對象」,而不是Ajax調用?

回答

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) 
     }); 
    } 
} 
3

複製的this值給另一個變量時,你仍然在this擁有你想要的值範圍內。

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

然後使用該變量(將在範圍爲在其內部聲明的函數,除非它們具有相同名稱的另一個變量掩蓋它)來代替。

success: function() { 
    console.log(myObject); 
} 
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) 
        } 
       }); 


      } 
     }); 
    } 
} 
+0

這不是語法上有效的Javascript。 – kevingessner 2013-04-25 16:36:52

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