我正在尝试了解 CoffeeScript 变量的范围。 根据文档:
This behavior is effectively identical to Ruby's scope for local variables.
但是,我发现它的工作方式不同。
在 CoffeeScript 中
a = 1
changeValue = -> a = 3
changeValue()
console.log "a: #{a}" #This displays 3
在 ruby 中
a = 1
def f
a = 3
end
puts a #This displays 1
有人能解释一下吗?
最佳答案
Ruby 的局部变量(以 [a-z_] 开头)are really local to the block they are declared in .所以你发布的 Ruby 行为是正常的。
在您的 Coffee 示例中,您有一个 closure引用一个。这不是函数声明。
在您的 Ruby 示例中,您没有闭包,而是函数声明。这是不同的。相当于你的 Coffee 的 Ruby 是:
a = 1
changeValue = lambda do
a = 3
end
changeValue()
在闭包中,声明 block 时存在的局部变量在执行 block 时仍然可以访问。这是闭包的(其中之一)力量!
关于ruby - 关于 CoffeeScript 变量范围的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9865661/