2011-09-25 19 views
0

考慮這個(?!?):的Javascript接力般的失敗

function f2(x) { 
    return x+1; 
}; 

X = function(){ 
    this.f1=function (x) { 
     return 2*f2(x); 
    } 

    return this; 
}; 

然後x = new X(); x.f1(1)工作正常。

但是,當我想這樣做:

X = function(){ 
    this.f2 = function(x) { 
     return x+1; 
    }; 

    this.f1=function (x) { 
     return 2*f2(x); 
    } 

    return this; 
}; 

相同的語句會抱怨它不能找到F2。 在,例如C#,你可以說

class X { 
    int f2(int x){return x+1;} 
    int f1(int x){return 2*f2(x);} 
} 

,這將工作

X x=new X(); 
x.f1(1) 

爲什麼?

回答

0

要在第二個代碼塊參照f2,你需要使用this.f2this引用函數正在執行的上下文。既然你以下面的方式調用f1

x.f1(); 

...的context設置爲實例,x

JavaScript不提供給在相同的方式,範圍變量的作用域實例變量,即那些直接提供:

X = function(){ 

    var f2 = 123; 

    this.f2 = function(x) { 
     return x+1; 
    }; 

    this.f1=function (x) { 

     console.log(f2); // => 123 
     console.log(this.f2); // => function(){} 

     return 2 * this.f2(x); 
    }; 

    return this; 
}; 
1

因爲你忘了這個 .f2。如果沒有這個,Javascript不會看到類變量

1

您需要明確引用帶有this關鍵字的f2。

X = function(){ 
    this.f2 = function(x) { 
     return x+1; 
    }; 

    this.f1=function (x) { 
     return 2*this.f2(x); 
    } 

    return this; 
}; 
0

JavaScript沒有隱含在C#中獲得的this。您需要添加這:

X = function(){ 
    this.f2 = function(x) { 
     return x+1; 
    }; 

    this.f1=function (x) { 
     return 2*this.f2(x); 
    }; 

    return this; 
}; 
0
X = function(){ 
     this.f2 = function(x) { 
      return x+1; 
     };  
     this.f1=function (x) { 
      return 2*this.f2(x); // <-- Need this here since it is not implicit 
     } 
     return this; 
    };