开发者

Javascript oop-like fail(?!?)

Consider this:

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

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

    return this;
};

then x = new X(); x.f1(1) works fine.

But when i want to do this:

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

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

    return this;
};

The same statement will complain that it can't find f2. In, for example c#, you can say

class 开发者_如何转开发X {
   int f2(int x){return x+1;}
   int f1(int x){return 2*f2(x);}
}

and this will work

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

Why?


You need to reference the f2 with the this keyword explicitly.

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

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

    return this;
};


because you forgot this.f2. Javascript don't see class variables without this


To reference f2 in your second code block, you'll need to use this.f2. this references the context in which the function is being executed. Since you call f1 in the following way:

x.f1();

... the context is set to the instance, x.

JavaScript does not make instance variables available to the scope in the same way as scope variables, i.e. those directly available:

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


Javascript doesn't have the implicit this that you get in C#. You need to add the this in:

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

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

    return this;
};


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜