KalEl
KalEl

Reputation: 9136

Javascript: Accessing superclass objects from nested class

a = new function() {
    this.x=2;
    B=function() {
        this.y=super.x;
    }
    this.b=new B();
}

alert(a.b.y); // Expecting 2

In the above, there is a parse error in super. How can I access the value of x when defining the class B?

Upvotes: 1

Views: 201

Answers (2)

KalEl
KalEl

Reputation: 9136

Found the best way to do this is to pass 'this' as the parameter in the constructor of the nested class, like this -

a = new function() {
    this.x=2;
    B=function(sup) {
        this.y=sup.x;
    }
    this.b=new B(this);
}

alert(a.b.y); // Displays 2

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

This works but i'm not sure that your code is correct

a = new function() {
    var x=2;
    B=function() {
        this.y=x;
    }
    this.b=new B();
}

alert(a.b.y); //alerts 2
alert(a.x) //alert undefined becuase x is private

in any case there is no super in javascript, if you read here you can see how you could implement inehritance in javascript through a uber method

Upvotes: 1

Related Questions