function testClass()
{
this.m_alert = "!!!";
this.body = document.body;
this.body.onclick = this.click;
}testClass.prototype.click = function()
{
alert(this.m_alert);
}window.onload = function()
{
try
{
var test = new testClass();
}
catch(e)
{
alert(e.messge);
}
}求教大家,我想通过将document.body与testClass类中body相关联,并且通过onclick来处罚click函数来输出testClass类中的m_alert成员变量,但是上述代码的运行结果为弹出undefined,这是则么回事,应该如何正确显示出m_alert的信息!!!,谢谢大家了(不好意思,我没有多少分数了)

解决方案 »

  1.   

    LZ试试这段代码就明白了
    <script>
    function testClass()
    {
        this.m_alert = "!!!";
        this.body = document.body;
        this.body.onclick = this.click;
    }testClass.prototype.click = function()
    {
        alert(this.m_alert);
    }window.onload = function()
    {
    document.body.m_alert = "this is body m_alert";
        try
        {
            var test = new testClass();
        }
        catch(e)
        {
            alert(e.messge);
        }
    }</script>
      

  2.   

    修改如下
    <script>
    function testClass()
    {
        this.m_alert = "!!!";
        this.body = document.body;
        this.body.onclick = this.click(this.m_alert);
        
    }testClass.prototype.click = function(v)
    {
        return function(){alert(v);}
    };window.onload = function()
    {
        try
        {
            var test = new testClass();
        }
        catch(e)
        {
            alert(e.messge);
        }
    }</script>
      

  3.   


    可为什么会这样呢,红色标记的this难道不是指testClass这个类吗?
      

  4.   

    这要看是谁触发的了
    <script>
    function testClass() 

        this.m_alert = "!!!"; 
        this.body = document.body; 
        this.body.onclick = this.click; 
    } testClass.prototype.click = function() 

        alert(this.m_alert);
    } window.onload = function() 

    document.body.m_alert = "this is body m_alert"; 
        try 
        { 
            var test = new testClass();
            test.click();//!!!
        } 
        catch(e) 
        { 
            alert(e.messge); 
        } 
    } </script>
    在body单击鼠标时,this肯定是指向body了
      

  5.   

    JavaScript中的this很灵活的,也很令人那迷糊的,呵呵。