2010-09-08 47 views
5

作爲一個正在嘗試採用更加面向對象的方法來編寫我的JavaScript編程的人,我碰到了一個絆腳石,我敢肯定它可能是非常基本的東西,但是,採取以下對象實現(假設jQuery對象是提供給這個代碼):JavaScript作用域問題

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

回答

6

您可以臨時使用另一個變量指向正確的

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

我知道它會是這樣簡單,謝謝:-) – 2010-09-08 17:44:22

5

在你輸入你傳遞給eachfunction,你需要捕捉外部函數的this一個變量,然後使用function內的變量,你傳遞給each

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

正如你已經找到了,this你傳遞給each功能的內部是指當前項jQuery對象中在每次迭代即第一次迭代是指項目在財產0,第二次迭代指在財產1等項目

0

你發現了USEF ul的JavaScript closures。它們對於製作簡潔的代碼非常強大和有用。這是您可以嘗試理解的最有用的JavaScript功能之一。