1

A sample bit of code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

<div id="myinfo">info</div>
<input id="clickme" type="button" value="click here to display info"/>

<script type="text/javascript">
    function Fighter() {
        this.name = "Kenny";    // fighters name
        this.hp = 10;           // fighters hp
        this.getHP = function() {
            return this.hp;
        }

        this.getName = function() {
            return this.name;
        }

        this.initUpdateButton = function(button_id) {
            $(button_id).click(function() {
                $("#myinfo").html("Name: "+this.getName()+"<br/>HP:"+this.getHP()); 
                // this.getName is undefined
            });
        }

    };

    var me = new Fighter();
    alert("Name: "+me.getName()+"<br/>HP:"+me.getHP()); // works properly
    me.initUpdateButton("#clickme"); // bind it to some ID
</script>

Simply put, given a JavaScript class with JQuery mixed in, I understand that on the callback for JQuery functions (i.e. $.click()), that this is referring to the object that was clicked and Not the Class or root function(). so this.getName() and this.getHP() don't work.

But what is the best way to get around this problem?

I saw some similar posts but they weren't of use to me so sorry if this is a repost and thanks in advance.

2
  • Is it really useful to have getter methods when your properties are public ? :) Commented Sep 23, 2010 at 2:57
  • Right, my actual implementation is not as simple as the example I whipped up for SO Commented Sep 23, 2010 at 3:34

1 Answer 1

2
this.initUpdateButton = function(button_id) {
            var self = this;
            $(button_id).click(function() {
                $("#myinfo").html("Name: "+self.getName()+"<br/>HP:"+self.getHP()); 
            });
        }
Sign up to request clarification or add additional context in comments.

1 Comment

oh wow. so simple. a definite sign that I should sleep a bit more before coding :-/ Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.