我想知道,在类属性和方法的声明中是否有互相引用的标准方法?例如:
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,但是经过多次重复后,它变得很混乱,我觉得这违反了类的目的。或者您可以通过其他方式延迟参考。有没有标准的方法可以做到这一点?
最好使用mixins
。同样,这在很大程度上取决于是否能够将对methodB的更改传播给A的所有后代,或者是否愿意。
如果不需要传播,则更加简单。
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
嗯,您总是可以实例化类中的另一个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(); //}
}