2

guys. I have something like this:

myThing = {
    str:"my string",
    setClick: function(){
        $("button").click(function(){
            alert(this.str);
        });
    }
}

myThing.setClick();

The problem is when I click the button the function doesn't know what str is. alert(str) gives me an error (str is not defined) and no alerts. alert(this.str) gives me the alert but containing undefined.

I can see that this reffers to the button and the button doesn't have any attribute called str. So how can I access the str that is out of jQuery's function?

3 Answers 3

5

Save a reference to this in setClick, outside the click event handler:

myThing = {
    str:"my string",
    setClick: function() {
        var self = this;
        $("button").click(function() {
            alert(self.str);
        });
    }
}

DEMO.

Sign up to request clarification or add additional context in comments.

Comments

3

You can always reference the object by name

myThing = {
    str:"my string",
    setClick: function(){
        $("button").click(function(){
            alert(myThing.str);
        });
    }
}

myThing.setClick();

Comments

0

You can force the context of a function using the javascript function bind. I find it can be useful in situations such as this. It lets you define the value of this within the function being bound.

myThing = {
    str:"my string",
    setClick: function(){
        $("button").click(function(e){
            // 'this' is myThing
            // $(e.currentTarget) is the button on which the event handler was attached
        }.bind(this));
    }
}

myThing.setClick();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.