如何在继承的类的同一个方法中使用在父类的超级方法中声明的变量

时间:2018-12-04 17:04:30

标签: javascript

例如,我们获得了A类:

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

及其子类B具有相同的方法:

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

当然,变量x在method中是未定义的。

但是我需要它。在类B的方法中获取它的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

由于您要从methodA()返回变量,因此您只能通过调用方接收它:

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()

另一种选择是将变量设置为实例变量,而不用var声明该变量,该变量将作用于函数。然后,您可以使用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()