开发者

Javascript and JQuery "this" scope errors

开发者 https://www.devze.com 2023-01-17 18:17 出处:网络
A sample bit of code: <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"></script>

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消