【发布时间】: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