【问题标题】:Javascript oop-like fail(?!?)Javascript oop-like 失败(?!?)
【发布时间】:2011-09-25 20:57:19
【问题描述】:

考虑一下:

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)

为什么?

【问题讨论】:

    标签: javascript oop function


    【解决方案1】:

    您需要使用 this 关键字显式引用 f2。

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

    【讨论】:

      【解决方案2】:

      因为你忘记了这个.f2。没有这个,Javascript 看不到类变量

      【讨论】:

        【解决方案3】:

        要在第二个代码块中引用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;
        };
        

        【讨论】:

          【解决方案4】:

          Javascript 没有 C# 中的隐式 this。您需要将 this 添加到:

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

          【讨论】:

            【解决方案5】:
            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;
                };
            

            【讨论】:

              猜你喜欢
              • 2011-07-25
              • 2020-06-29
              • 1970-01-01
              • 1970-01-01
              • 2021-03-15
              • 1970-01-01
              • 2019-04-04
              • 2021-12-05
              • 1970-01-01
              相关资源
              最近更新 更多