如何从jQuery函数访问外部的这个?

时间:2011-04-11 01:05:49

标签: javascript jquery this

出于好奇,有没有办法从this.color功能访问paint

function Foo(color)
{
    this.color = color;
    this.paint = function paint()
    {
       $("select").each(function(idx, el)
        {
            $(el).css("background", color); // OK
            // $(el).css("background", this.color); // this.color is undefined
        })
    }
}

new Foo("red").paint();

由于

1 个答案:

答案 0 :(得分:10)

var that = this;
function (idx, el) {
    // access what used to be this.color as that.color
}