javascript - 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 ?
解决方案
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()
推荐阅读
- corda - 如何更改公证人配置?
- amazon-web-services - DynamoDB:读/写容量是如何计算的?如果快速扩展,这意味着什么(对于免费层)?
- apache-nifi - 什么是 NIFI 数据转换中的牧马人端口?
- laravel - 使用 Laravel 的 S3 中不存在文件,即使它存在
- ios - Swift 侧边菜单滑动打开
- google-sheets - 使用 Google 电子表格公式动态获取经过的分钟数
- kotlin - 面向多平台时测试方法名称中的空格
- google-apps-script - 将 Excel 文件导入 Google 数据表
- gcloud - 从命令行(谷歌云)为实例分配保留 IP
- node.js - 如何在猫鼬中添加运算符