【问题标题】:Is there a standard way for Javascript classes to refer to each other?Javascript类是否有一种标准的方式来相互引用?
【发布时间】:2020-05-29 18:23:28
【问题描述】:

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

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


    【解决方案1】:

    首先,Javascript 没有“类”。 class 关键字只是为了让它看起来很熟悉。它应该是 proto 而不是 class

    最好使用mixins。此外,这在很大程度上取决于是否能够将对方法 B 的更改传播给 A 的所有后继者,或者您是否愿意。

    另见"prose-like syntax"

    不传播 - 复制

    如果你不需要传播并且你需要将很多方法复制过来:

    const A = {
        name: 'I am A.'
    }
    
    const B = {
        name: 'I am B.', // this will overwrite A when we #assign. so be careful to assign it back
        methodB() {
            console.log(`${this.name} - foo`)
        }
    }
    
    const a = Object.create(A)
    
    Object.assign(a, B)
    a.name = A.name
    
    // methodB is changed but it won't propagate.
    B.methodB = function() {
        console.log(`${this.name} - bar`)
    }
    
    a.methodB() // I am A. - foo
    B.methodB() // I am B. - bar
    

    有传播。

    如果您只需要一种或几种方法:

    const A = {
        name: 'I am A.'
    }
    
    const B = {
        name: 'I am B.',
        methodB() {
            console.log(`${this.name} - foo`)
        }
    }
    
    const a = Object.create(A)
    
    a.methodA = function() {
        B.methodB.call(this)
    }
    
    B.methodB = function() {
        console.log(`${this.name} - bar`)
    }
    
    a.methodA() // I am A. - bar
    B.methodB() // I am B. - bar
    

    【讨论】:

      【解决方案2】:

      好吧,你可以一直在你的类中实例化另一个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(); //}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多