Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5622

Access values of object from within a javascript closure

I can't get how to access that value, this is my code:

function Filters()
{
    this.filters = ["filter_1", "filter_2", "filter_3"];
    this.someData = "test";
    this.draw = draw;
    function draw(){
        for(var i=0; i<this.filters.length;i++)
        {
            var filter = this.filters[i];
            $("#" + filter).click(function(){
                doSomething();
            });
        }
    }
    function doSomething(){
        alert(this.someData);
    }
}

I am aware of the fact that since doSomething() is called from within the closure, this. will refer a JQuery object being worked on. So how do I go about being able to use someData from my object in that function/closure ? Can't seem to figure it out.
Thanks for help :)

Upvotes: 0

Views: 165

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

No, this inside doSomething will be the global object. You need to keep a reference to this in a separate variable:

function Filters()
{
    var that = this; // reference to this
    this.filters = ["filter_1", "filter_2", "filter_3"];
    this.someData = "test";
    this.draw = draw;
    function draw(){
        for(var i=0; i<this.filters.length;i++)
        {
            var filter = this.filters[i];
            $("#" + filter).click(function(){
                doSomething();
            });
        }
    }
    function doSomething(){
        alert(that.someData);
    }
}

Unrelated to your problem: you could also pass a reference to doSomething as the event listener, instead of wrapping it in another function:

$("#" + filter).click(doSomething);

Upvotes: 1

Related Questions