在 ES6 中从一个 class 访问对象到另一个
Accessing objects from one class to another in ES6
首先,对于我刚接触 ES6 javascript 提出这个问题,我深表歉意。我的 class 结构类似于 -
文件名 - Ab.js
class A{
method A(){
const a = '1'
//could have more const in this method
}}
class B{
method B(){
const b='2'
//could have more const in this method
}}
现在我想在另一个文件中访问这个 class 说 C.js
class c{
method c()
{
//here I want to access A and B like
const c= A.A.a // this should return 1
}}
但是我尝试通过在 Ab.js 中导出默认值 class 并在 C.js 中导入相同的值,我能够访问 C.js 中对象的值但如果你在 Ab.js 中有多个 class,这是不允许的。我可以知道为什么吗? .. 任何解决方案将不胜感激。
使用静态方法和return一个对象:
class A {
static A(a = 1, b = 2) {
return { a, b };
}
}
用法:
A.A().a; // 1
A.A().b; // 2
首先,对于我刚接触 ES6 javascript 提出这个问题,我深表歉意。我的 class 结构类似于 -
文件名 - Ab.js
class A{
method A(){
const a = '1'
//could have more const in this method
}}
class B{
method B(){
const b='2'
//could have more const in this method
}}
现在我想在另一个文件中访问这个 class 说 C.js
class c{
method c()
{
//here I want to access A and B like
const c= A.A.a // this should return 1
}}
但是我尝试通过在 Ab.js 中导出默认值 class 并在 C.js 中导入相同的值,我能够访问 C.js 中对象的值但如果你在 Ab.js 中有多个 class,这是不允许的。我可以知道为什么吗? .. 任何解决方案将不胜感激。
使用静态方法和return一个对象:
class A {
static A(a = 1, b = 2) {
return { a, b };
}
}
用法:
A.A().a; // 1
A.A().b; // 2