2010-09-08 26 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功能之一。