<script>
function Debug(num){
this.num = num;
this.out = function(){
alert(this.num);
}
}
var dbg = new Debug(555);
</script>
<body>
<div id="Layer1">clickme</div><script>document.getElementById('Layer1').onclick = function(){dbg.out();}</script>
</body>

解决方案 »

  1.   

    Carignano(Carignano) 这个方法可行,请问
    我把 onclick 函数注册为 dbg.out 为什么得不到想要的结果呢?
      

  2.   

    你这样写
    document.getElementById('Layer1').onclick = dbg.out;
    实际执行时alert(this.num)中的this指的是Layer1,
    下面这样写
    document.getElementById('Layer1').onclick = function(){dbg.out();}
    alert(this.num)中的this才指的是Debug的实例。你可以将alert(this.num)改为alert(this.id)试一下就知道了。
      

  3.   

    <!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=gb2312" />
    <title>js问题</title>
    <style type="text/css">
    <!--
    #Layer1 {
    width:87px;
    height:56px;
    z-index:1;
    background-color: #CCCCCC;
    }
    -->
    </style>
    </head>
    <script>
    function Debug(num){
    this.num = num;
    }this.out = function(){
    alert(num);
    //alert("dfdfdfsdfds");
    }var dbg = new Debug(555);
    var gjp = "hello world";
    </script>
    <body>
    <!-- 如果直接写到div则可以正常显示 数字555
    <div id="Layer1" onclick="dbg.out()">clickme</div>
    -->
    <div id="Layer1" >clickme</div>
    <script>
    document.getElementById('Layer1').onclick = dbg.out;
    </script>
    </body>
    </html>
    我修改了一下你的Debug函数。其中
    this.out = function(){
    alert(this.num);
    }
    改为
    this.out = function(){
    alert(num);
    }
    就可以达到你要的结果了。具体原因是JS是this的用法和一般的面向对象的用法有不同的地方。
    在JS中this就是引用函数级的。所以你用this.num在你的out函数中没有定义。所以显示时undefine.
      

  4.   

    this指的是运行时的对象 也就是'Layer1' 而不是定义时的对象(Debug)
      

  5.   

    感谢 Carignano(Carignano) wzhiyuan(我是谁)
    还有个小问题问一下 tjgjp()所写的 
    "this.out = function(){
    alert(this.num);
    }
    改为
    this.out = function(){
    alert(num);
    }"这样document.getElementById('Layer1').onclick = dbg.out;
    就可以正确执行了   可是 num 只是一个对象构造时的参数, 而 dbg.out这个函数是被语法copy到Layer1对象中的(this的指向都被更换了)
    他又怎么能知道num的存在的呢?可能问题提的有点没水平,请大家见谅, 谢谢
      

  6.   

    haothing(haothing) 所说的“this指的是运行时的对象 也就是'Layer1' 而不是定义时的对象(Debug)”确实有道理。受教了。呵呵。
    不过,我的那种方法就是单纯从静态方面考虑的,也就是用面向对象的方法看问题,这样不用容易引起混乱。毕竟JS是一种动态的非编译性的语言。所以它很灵活,所以一种结果,可以有很多种的表现形式。所以这也是JS的魅力所在。呵呵
      

  7.   

    wanted
    [5wCntid]
    adj.
    wanted by the police 被通缉的