JavaScript范围问题

JavaScript范围问题,javascript,oop,scope,Javascript,Oop,Scope,作为一个试图对我的javascript编程采取更面向对象方法的人,我遇到了一个绊脚石,我相信这可能是非常基本的,但是,以下面的对象实现为例(假设jQuery对象可用于此代码): 在输入传递给每个的函数之前,需要捕获变量中外部函数的此,然后使用传递给每个的函数中的变量 function Foo() { this.someProperty = 5; } Foo.prototype.myFunc = function() { //do stuff... }; Foo.prototy

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


在输入传递给
每个
函数之前,需要捕获变量中外部函数的
,然后使用传递给
每个
函数中的变量

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

正如您所发现的,
这个
在传递给
的函数中,每个
在每次迭代中都引用jQuery对象中的当前项,即第一次迭代引用属性0处的项,第二次迭代引用属性1处的项,等等。

您可以临时使用另一个变量来指向正确的

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

    var self = this;

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

你正在发现这个方法的有用性。它们非常强大,对于编写简洁的代码非常有用。这是您可以尝试理解的最有用的JavaScript特性之一

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

    var self = this;

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