foo.咖啡:
class Foo
constructor: ->
console.log BAR
module.exports = Foo
主.咖啡:
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 中,当您声明变量时,它总是被编译为局部变量。
因此,在上面的声明中,当您执行 BAR=1
时,它会编译为 var BAR=1
。因此,该变量的作用域始终是本地的,这意味着其他模块无法访问它。
因此,Jed Schneider 为您提供的解决方案是正确的,但有一点需要注意,在 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 中。这样您的 this
就指向 global
而不是 module.exports
。
因此,这会产生您预期的结果:
do ->
@BAR = 1
class Bar
constructor: ->
console.log BAR
new Bar()
Foo = require './foo'
new Foo()
这会产生输出
1
1
关于javascript - module.exports 和外部范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24284428/