JavaScript作用域问题

5

作为一个试图以更面向对象的方式编写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个回答

6
您可以暂时使用另一个变量指向正确的this
Foo.prototype.bar = function()
{
    //here 'this' refers to the object Foo
    console.log(this.someProperty);

    var self = this;

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

5

在进入你传递给eachfunction之前,你需要将外部函数的this捕获到一个变量中,然后在你传递给eachfunction内部使用该变量。

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

正如你所发现的那样,在传递给each的函数内部,this指的是jQuery对象中每次迭代的当前项,即第一次迭代指的是属性0处的项,第二次迭代指的是属性1处的项,以此类推。


0

你正在探索JavaScript闭包的用处。它们非常强大,有助于编写简洁的代码。这是你可以尝试理解的最有用的JavaScript特性之一。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接