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

Pao*_*olo 9 javascript jquery this

出于好奇,有没有办法this.colorpaint功能访问?

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();
Run Code Online (Sandbox Code Playgroud)

谢谢

Ale*_*rge 10

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

  • 还有一个问题:这就是所谓的"封闭"吗? (2认同)
  • @Guandalino是的,这是一个关闭. (2认同)