Javascript类是否有互相引用的标准方法?

问题描述 投票:0回答:2

我想知道,在类属性和方法的声明中是否有互相引用的标准方法?例如:

class A {
  methodA(){
    b.methodB()
    ...
  }
}

class B {
  methodB(){...}
}

const a = new A();
const b = new B(); 

///will throw ReferenceError: Cannot access 'b' before initialization;

我知道您可以稍后在所有类/对象声明之后添加methodA,但是经过多次重复后,它变得很混乱,我觉得这违反了类的目的。或者您可以通过其他方式延迟参考。有没有标准的方法可以做到这一点?

javascript class oop hoisting
2个回答
1
投票

最好使用mixins。同样,这在很大程度上取决于是否能够将对methodB的更改传播给A的所有后代,或者是否愿意。

另请参阅"prose-like syntax"

无传播-复制

如果不需要传播,则更加简单。

const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.',
    methodB() {
        console.log('foo')
    }
}

const a = Object.create(A)

Object.assign(a, B)

a.methodA = function() {
    this.methodB()
}

B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodA() // I am A. - foo

随着传播。

const A = {
    name: 'I am A.'
}

const B = {
    name: 'I am B.',
    methodB() {
        console.log(`${this.name} - foo`)
    }
}

const a = Object.create(A)

a.methodB = function() {
    B.methodB.call(this)
}
a.methodA = function() {
    this.methodB()
}

B.methodB = function() {
    console.log(`${this.name} - bar`)
}

a.methodA() // outputs I am A. - bar

0
投票

嗯,您总是可以实例化类中的另一个classes,例如A,并像这样访问它们的方法和属性。

class A {
  methodA(){
    const b = new B(); 
    b.methodB()
  }
}

class B {
  methodB(){console.log("Here I am")}
}

const a = new A();
a.methodA();

或者,您可以使用inheritance

class A {}
class B extends A{
 constructor() { super(); //}
}
© www.soinside.com 2019 - 2024. All rights reserved.