module.exports和外部范围
foo.coffee:
class Foo constructor: -> console.log BAR module.exports = Foo
main.coffee:
BAR = 1 class Bar constructor: -> console.log BAR new Bar() Foo = require './foo' new Foo()
然后
$ coffee main.coffee 1 ReferenceError: BAR is not defined
为什么在Foo
的实例中不能访问BAR
? 我可以使它对Foo
对象“可见”(除了显式传递给构造函数外)吗?
我认为问题是在CoffeeScript中,当你声明一个variables时,它总是被编译成一个局部variables。
因此,在上面的声明中,当你做BAR=1
,编译成var BAR=1
。 所以,variables总是在本地范围内,这意味着它不能被其他模块访问。
所以,Jed Schneider给你的解决scheme是正确的,只有一个警告,在Node.js中,当你在一个模块中时, this
引用指向module.exports
对象,而不是Jed显得的global
对象(这是node.js和浏览器之间的混淆之源,因为在浏览器中的行为与Jed解释的一样)。
所以,这总是如此
//module.js console.log(this==module.exports) //yield true
而在一个函数内, this
关键字将指向全局对象。 所以,这也是事实:
//module.js (function(){ console.log(this==global); //yields true })()
正因为如此,为了解决您的问题,您可以使用Jed Schneider方法,但要确保将代码封装在一个IIFE中,以便您的代码指向global
而不是module.exports
。
所以,这会产生您的预期结果:
do -> @BAR = 1 class Bar constructor: -> console.log BAR new Bar() Foo = require './foo' new Foo()
这产生输出
1 1
class Bar constructor: -> console.log @BAR
然后设置
@BAR = 1
应该做你期望的事情。 这是这个速记this.
这将把它放在全局对象上,就像你期待的常量被定义一样。 亲自,我会做一个常量命名空间和导出,就像你做Foo
。