如何从jQuery函数访问外部this

How to access the outer this from jQuery functions?

本文关键字:访问 外部 this 函数 jQuery      更新时间:2023-09-26

出于好奇,是否有办法从paint函数访问this.color ?

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

谢谢

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