【问题标题】:Javascript and JQuery "this" scope errorsJavascript 和 JQuery “this”范围错误
【发布时间】:2011-04-16 00:55:52
【问题描述】:

一段代码示例:

<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>

简单地说,给定一个混合了 JQuery 的 JavaScript 类,我知道在 JQuery 函数的回调中(即$.click()),this 指的是被点击的对象,而 不是 类或根函数()。所以this.getName()this.getHP() 不起作用。

但是解决这个问题的最佳方法是什么?

我看到了一些类似的帖子,但它们对我没有用,如果这是转发,我很抱歉,提前致谢。

【问题讨论】:

  • 当你的属性是 public 时,拥有 getter 方法真的有用吗? :)
  • 对,我的实际实现并不像我为 SO 准备的示例那么简单

标签: javascript jquery scope this


【解决方案1】:
this.initUpdateButton = function(button_id) {
            var self = this;
            $(button_id).click(function() {
                $("#myinfo").html("Name: "+self.getName()+"<br/>HP:"+self.getHP()); 
            });
        }

【讨论】:

  • 哇哦。很简单。一个明确的迹象表明我应该在编码之前多睡一会儿:-/谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-07-02
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
相关资源
最近更新 更多