2010-09-08 24 views
5

Javascript programlamaya daha fazla nesne yönelimli bir yaklaşım benimsemeye çalışan birisi olarak, muhtemelen çok temel bir şey olduğunu düşündüğüm tökezleyen bir bloğa rastladım, ancak aşağıdaki nesne uygulamasını al (varsayalım jQuery nesnesi) bu koda mevcuttur:JavaScript Kapsam soru

function Foo() 
{ 
    this.someProperty = 5; 
} 

Foo.prototype.myFunc = function() 
{ 
    //do stuff... 
}; 

Foo.prototype.bar = function() 
{ 
    //here 'this' refers to the object Foo 
    console.log(this.someProperty); 

    $('.some_elements').each(function() 
    { 
     //but here, 'this' refers to the current DOM element of the list of elements 
     //selected by the jQuery selector that jquery's each() function is iterating through 
     console.log(this); 

     //so, how can i access the Foo object's properties from here so i can do 
     //something like this? 
     this.myFunc(); 
    }); 
}; 

cevap

6

vb mülkiyet 1, en madde düzgün bu işaret edecek:

Foo.prototype.bar = function() 
{ 
    //here 'this' refers to the object Foo 
    console.log(this.someProperty); 

    var self = this; 

    $('.some_elements').each(function() 
    { 
     self.myFunc(); 
    }); 
}; 
+0

Bunun gibi basit bir şey olacağını biliyordum, teşekkürler :-) –

5

Eğer each geçmek function, bir değişkene dış fonksiyonun this yakalamak ve daha sonra function iç değişken kullanmak gerekir girmeden önce o sen each'a geçin. Eğer öğrendim gibi

function Foo() 
{ 
    this.someProperty = 5; 
} 

Foo.prototype.myFunc = function() 
{ 
    //do stuff... 
}; 

Foo.prototype.bar = function() 
{ 
    // in here, this refers to object Foo 

    // capture this in a variable 
    var that = this; 

    $('.some_elements').each(function() 
    { 
     // in here, this refers to an item in the jQuery object 
     // for the current iteration 

     console.log(that); 
     that.myFunc(); 
    }); 
}; 

, sen each geçmek işlev içinde this her yineleme yani birinci tekrar jQuery nesnesi geçerli öğeye atıfta mülkiyet 0 öğeye karşılık gelir, ikinci yineleme belirtir geçici olarak başka bir değişken kullanabilirsiniz

0

Sen usef keşfediyoruz JavaScript closures'un ulnessi. Özlü kod yapmak için inanılmaz derecede güçlü ve kullanışlılar. Bu, anlamaya çalışabileceğiniz en kullanışlı JavaScript özelliklerinden biridir.