function Person(id, name, age)
{
this.id = id;
this.name = name;
this.age = age; $("#txt1").click(function()  //txt1是一个文本框,点击时显示人的信息
{
$(this).val(id + "/" + name + "/" + age);
//ShowInfo();   //怎么调用Person的方法?
});
}Person.prototype.ShowInfo = function()
{
alert("id: " + this.id + "\r\nname:" + this.name + "\r\nage:" + this.age);
}$(function()
{
var p = new Person("123", "zhang", 20);
p.ShowInfo();
});在文本框的click事件中调用当前对象Person的自定义方法,怎么做(不考虑类及调用的合理性,只为说明问题)? 

解决方案 »

  1.   

    方法是调用了,但显示undefined,和直接p.ShowInfo()调用结果不一样,熟悉js原理的解释一下不,tks.
    id: undefined
    name:undefined
    age:undefined
      

  2.   

    jquery事件中的this指向绑定事件的对象,即txt1。访问属性不能加this,事件也一样了。
    $(this).val(id ...); 不能用$(this).val(this.id ...);
      

  3.   

    var p = new Person(id, name, age)
    p.ShowInfo();既然构造中需要参数,那么你必须传递参数
      

  4.   


     function Person(id, name, age) {
              this.id = id;
              this.name = name;
              this.age = age;
              var _this = this;//保存this
              $("#txt1").click(function () 
              {
                  $(this).val(id + "/" + name + "/" + age);             
                  _this.ShowInfo()//调用_this
              });
          }
      

  5.   

    这种是最好的 
    要内部函数中使用当前对象的方法  因为变量的作用域问题 要把this提出 当做一个小的全局变量使用