1
的代码样本位:Javascript和JQuery的“本”范围的错误
<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>
简单地说,给定一个JavaScript类使用jQuery混合,据我所知,在回调jQuery的功能(即$.click()
) this
指的是被点击的对象,而不是类或根函数()。所以this.getName()
和this.getHP()
不起作用。
但是,解决这个问题的最好方法是什么?
我看到一些类似的帖子,但他们对我没有用,所以很抱歉,如果这是一个转发和预先感谢。
当你的属性公开时,getter方法真的有用吗? :) – 2010-09-23 02:57:57
对,我的实际执行情况并不像我为SO – 2010-09-23 03:34:47