function methodObj(){
    this.p1;
    this.p2 = (function(){
        return this.p1 * 2;
    })();
   
}var obj = new methodObj();alert(obj.p2);  // obj.p2 value is undefined想问的是红色字体部分.正确的写法应该是怎样的?  函数体内引用不到 this.p1

解决方案 »

  1.   

    function methodObj(){
        this.p1;
        this.p2 = (function(){
            return this.p1 * 2;
        })();
       
    }var obj = new methodObj();alert(obj.p2);  // obj.p2 value is undefined
      

  2.   

    域不一样,this指向不同
    你可以把this.p1作为参数传进去,如:this.p2 = (function(x){return  x* 2;})(this.p1);
    或定义一变量,如:var x = this.p1; this.p2 = (function(){return  x* 2;})();
      

  3.   

    有办法使嵌套函数的域指向被嵌套的函数里吗?用call什么的.有办法实现吗
      

  4.   

    <script>
    function methodObj(){
        this.p1=2
        this.p2 = function(arg){return arg * 2}.call(this, this.p1)
    }var obj = new methodObj();alert(obj.p2);  // obj.p2 value is undefined
    </script>
      

  5.   

    this.p2 = (function(){ 
        return this.p1 * 2; 
    }).call(this);