Javascript类oop失败(?!?)
考虑这一点:Javascript类oop失败(?!?),javascript,oop,function,Javascript,Oop,Function,考虑这一点: function f2(x) { return x+1; }; X = function(){ this.f1=function (x) { return 2*f2(x); } return this; }; 然后x=newx();x、 f1(1)工作正常 但当我想这样做时: X = function(){ this.f2 = function(x) { return x+1; }; thi
function f2(x) {
return x+1;
};
X = function(){
this.f1=function (x) {
return 2*f2(x);
}
return this;
};
然后x=newx();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)
为什么?因为你忘了这个。Javascript在并没有这个的情况下看不到类变量,您需要使用this关键字显式地引用f2
X = function(){
this.f2 = function(x) {
return x+1;
};
this.f1=function (x) {
return 2*this.f2(x);
}
return this;
};
Javascript没有C#中的隐式
this
。您需要在此中添加以下内容:
X = function(){
this.f2 = function(x) {
return x+1;
};
this.f1=function (x) {
return 2*this.f2(x);
};
return this;
};
X=function(){
this.f2=函数(x){
返回x+1;
};
this.f1=函数(x){
返回2*this.f2(x);//以引用第二个代码块中的f2
,您需要使用this.f2
此
引用执行函数的上下文。由于您以以下方式调用f1
:
x.f1();
…将上下文设置为实例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;
};
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;
};