2012-06-15 61 views
2

我在JavaScript中有以下類:如何防止jQuery來越權「這個」

function User(aJid){ 
    this.jid = aJid; 
    this.name = ''; 
    this.uni = ''; 
    this.edad = ''; 
    this.foto = ''; 
    this.avatar = ''; 
    this.initialize2 = function(){ 

     $('#edit_vcards').on('click', '#enviar_vcard', function(){ 
      //alert("enviando..."); 
      console.log(this); 
     }); 
    }; 

正如你可以看到我有結合到DOM一些元素的功能的方法「initialize2」。在那裏我做一個console.log(this),它打印我們綁定方法的DOM元素,而不是執行方法initialize2的對象。我如何從該函數訪問該對象? 就好像綁定的函數的範圍是整個DOM而不是對象。無論如何做我想做什麼?

+3

超過九千重複 – Esailija

回答

10
function User(aJid){ 
    this.jid = aJid; 
    this.name = ''; 
    this.uni = ''; 
    this.edad = ''; 
    this.foto = ''; 
    this.avatar = ''; 
    this.initialize2 = function(){ 
    var that = this; //store a reference to maintain scope 

     $('#edit_vcards').on('click', '#enviar_vcard', function(){ 
      //alert("enviando..."); 
      console.log(that); //use that variable here 
     }); 
    }; 
2

嘗試通過obj this.on和處理程序內部,您可以使用event.data訪問obj this。見下文,

this.initialize2 = function(){ 

    $('#edit_vcards').on('click', '#enviar_vcard', {obj_this: this }, function(){ 
     //alert("enviando..."); 
     console.log(event.data.obj_this); //should be the obj this 
    }); 
}; 
0

經過外部this通過event.data

$('#edit_vcards').on('click', { outerThis: this }, function (event) { 
    console.log(event.data.outerThis); 
});