首页 > 解决方案 > How to use a variable declared in super method of parent Class inside same metod of inherited Class

问题描述

For example we got class A :

class A {
    methodA() {
        let x = 1
        //do something with x
        return x
    }
}

and its child class B with same method :

class B extends A {
    metodA() {
        super.metodA() 
        //how to get a var x here ?
        //dosomething with x
    }
}

of course variable x is undefined inside method .

But i need it . What is best way to get it inside method of class B ?

标签: javascript

解决方案


Since you are returning the variable from methodA() you can just receive it with the caller:

class A {
    methodA() {
        let x = "Some Value from A"
        //do something with x
        return x
    }
}

class B extends A {
    methodA() {
        let x = super.methodA() 
        console.log("x:", x)
        //how to get a var x here ?
        //dosomething with x
    }
}

let b = new B
b.methodA()

An alternative would be to set the variable as an instance variable rather than declaring it with var which will be scoped to the function. Then you can retrieve it with this.x:

class A {
    methodA() {
         this.x = "Some Value"
        //do something with this.x
    }
}

class B extends A {
    methodA() {
        super.methodA() 
        console.log("x:", this.x)
    }
}

let b = new B
b.methodA()


推荐阅读