Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the outer this from jQuery functions?

out of curiosity is there a way to access this.color from the paint function?

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

Thanks

like image 902
Paolo Avatar asked Apr 11 '11 01:04

Paolo


1 Answers

var that = this;
function (idx, el) {
    // access what used to be this.color as that.color
}
like image 126
Alec Gorge Avatar answered Nov 05 '22 17:11

Alec Gorge