Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript类oop失败(?!?)_Javascript_Oop_Function - Fatal编程技术网

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;
};