在 Coffeescript 中访问静态属性

Accessing static properties in Coffeescript

记住下面的代码

a.coffee

B = require './b'
C = require './c'

console.log B.someStaticVar
C.checkB()

b.coffee

C = require './c'

class B
  @someStaticVar: 1

module.exports = B;

c.coffee

B = require './b'

class C
  @checkB: ->
    console.log B.someStaticVar

module.exports = C

我试图理解为什么 b 的静态 属性 在被 c 访问但返回 1 当被 a

访问时

输出:

$ coffee a.coffee
1
undefined

看起来你有一个循环引用。

  1. A加载B
  2. B加载C
  3. C加载B
    • 但是B还没有完成加载,所以这里是一个空对象
  4. C 完成加载
  5. B 完成加载
  6. A 加载 C - 它已经加载,所以它只是获取一个引用。
  7. A 完成加载,执行文件末尾的 console.log 行。

这是您的 3 个模块的一个版本,可以更好地说明这一点:

a.coffee

B = require './b'
C = require './c'
console.log B.someStaticVar
C.checkB()

b.coffee

C = require './c'
console.log 'in b.coffee, we have loaded C: ', C
class B
  @someStaticVar: 1
module.exports = B;

c.coffee

B = require './b'
console.log 'in c.coffee, we have loaded B: ', B
class C
  @checkB: ->
    console.log B.someStaticVar
module.exports = C

你有两种选择来修复 commonjs 中的这种循环依赖:

1。延迟加载

在执行函数之前,不要在 c.coffee 中要求 ./b。当您在 a.coffee 中调用 C.checkB 时,B 已经完全加载,并且将从 require 调用

返回正确的 class
class C
  @checkB: ->
    B = require './b'
    console.log B.someStaticVar

module.exports = C

2。重构

BC 紧密耦合。考虑重写它们以包含在单个文件中。您可以从 b.coffee 中删除 require './c'。虽然我猜它在这个例子中是因为你的代码更复杂并且确实需要它。

a.coffee

{ B, C } = require './b'

console.log B.someStaticVar
C.checkB()

b.coffee

class B
  @someStaticVar: 1

class C
  @checkB: ->
    console.log B.someStaticVar

module.exports = 
  C: C
  B: B