问个很菜的问题,代码如:function c1(){
this.o1=100;
function p1(){
return this.o1+42
}
function p2(){
return 52
}
this.q1=p1()+1;
this.q2=p2()+2;
}
a1=new c1()
alert(a1.q1);//NaN
alert(a1.q2);//54为什么p1()调用的this.o1会无效呢?p1()的作用域在哪?

解决方案 »

  1.   


    function c1(){
        this.o1=100;
        var $this = this;
        function p0(){
            return $this.o1+42
        }
        function p1(){
            return this.o1+42//这里this是代表p1而不是c1
        }    function p2(){
            return 52
        }
        this.q0=p0();
        this.q1=p1()+1;
        this.q2=p2()+2;
    }
    a1=new c1()
    alert(a1.q0);
    alert(a1.q1);//NaN
    alert(a1.q2);//54
      

  2.   


    this始终指向到调用它的对象。<script type="text/javascript">function c1(){
        this.o1=100;
        function p1(){
    alert(arguments.callee.caller==c1);//p1中的this始终指向到c1
            return this.o1+42
        }
        function p2(){
    alert(arguments.callee.caller==c1);//p2中的this始终指向到c1
            return 52
        }
        this.q1=p1()+1;
        this.q2=p2()+2;
    }alert(c1.o1);//c1未被实例化的时候无法访问到构造内部的属性。var a = new c1();alert(a.o1+'\n'+a.q1+'\n'+a.q2);</script>
      

  3.   

    补充一点:function c1(){
    alert(arguments.callee.caller);//c1的调用对象是window
    //other...
    }
      

  4.   

    window.o1 = 1;function c1(){
        this.o1=100;
        function p1(){
            return this.o1+42
        }
        function p2(){
            return 52
        }
        this.q1=p1()+1;
        this.q2=p2()+2;
    }
    a1=new c1()
    alert(a1.q1);//NaN
    alert(a1.q2);//54this其实是window
      

  5.   

    风之石说的好像有点问题哦arguments.callee.caller得到的是程序在哪个函数中执行
    并不是调用它的对象哦
      

  6.   

    lz可以参照这个
    function c1(){
        this.o1=100;
        this.p1 = function(){
            return this.o1+42
        }
        function p2(){
            return 52
        }
        this.q1=this.p1()+1;
        this.q2=p2()+2;
    }a1=new c1()
    alert(a1.q1);//NaN
    alert(a1.q2);//54
      

  7.   


    window.o1 = 1;function c1(){
        this.o1=100;
        function p1(){
            alert(arguments.callee.caller);
    return this.o1
        }
        this.p2=function(){
            alert(arguments.callee.caller);
    return this.o1
        }
        this.q1=p1()+1;
        this.q2=this.p2()+2;
    }
    a1=new c1()
    alert(a1.q1);//NaN
    alert(a1.q2);//54两个的this不是同一个对象但arguments.callee.caller都是相同的
    解析不了this吧