test.prototype.testClick=function()
{
var button1 = document.getElementById("button1");
button1.onclick=function()
{
alert(this.testName);//这个this指向button1而非test对象本身
}
}

解决方案 »

  1.   

    To duwa789:
    是的,请问有什么办法把test对象testName的值alert显示出来吗?
      

  2.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <title>Untitled 1</title>    <script type="text/javascript">
        var Class = {
            create : function () {
                return function () {
                    this.initialize.apply (this,arguments);
                }
            }
        }    
        
        var $ = function (id) {
            return document.getElementById(id);
        }
        
        var test = Class.create();    test.prototype = {
            initialize : function (name) {        
                var t = this;            
                t.testName = name;
            },
            testName  : null,
            testClick : function (btnid) {
                var t = this;            
                var button1 = $(btnid);
                button1.onclick = function () {
                    alert(t.testName);
                }
            }
        }
        
        </script>
    </head>
    <body>
        <button id="button1">
            test</button>
        <script type="text/javascript">
        var t = new test('Andy');
        t.testClick('button1');
        </script>
    </body>
    </html>
      

  3.   

    因为js是动态解释的,所以函数由哪个对象触发,this就指向那个对象~~~
    相对于预编译的语言~这点很有特色~~~
      

  4.   

    789的代码虽然好,但是不是太容易理解,主要就是那一句t=this这句,按照你的代码改下的话就是
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled 1</title>
    <script type="text/javascript">
    function test(newName)
    {
    this.testName = newName;
    }
    test.prototype.testClick=function()
    {
    var button1 = document.getElementById("button1");
    var t=this
    button1.onclick=function()
    {
    alert(t.testName);
    }
    }
    </script>
    </head>
    <body>
    <button id="button1">test</button>
    <script type="text/javascript">
    var t = new test('Andy');
    t.testClick();
    </script>
    </body>
    </html>