JavaScript范围问题

时间:2010-09-08 17:23:31

标签: javascript oop scope

作为一个试图采用更加面向对象的方法进行我的javascript编程的人,我遇到了一个绊脚石,我肯定这可能是非常基本的东西,但是,采取以下对象实现(假设jQuery对象)可用于此代码):

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

3 个答案:

答案 0 :(得分: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();
    });
};

答案 1 :(得分:5)

在您输入传递给function的{​​{1}}之前,您需要捕获变量中外部函数的each,然后使用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是指每次迭代时jQuery对象中的当前项,即第一次迭代引用属性0处的项,第二次迭代是指属性1等的项目

答案 2 :(得分:0)

您正在发现JavaScript closures的用处。它们非常强大,可用于制作简洁的代码。这是您可以尝试理解的最有用的JavaScript功能之一。