Ruby 的“绑定”是吗?和作用域链一样吗?
Ruby 的 eval()
可以像
def showblock(&block)
puts eval("i * 3", block)
end
其中 block 是传递到函数中的块。
除了块之外,还可以传入绑定对象。绑定对象和讨论Javascript闭包时经常提到的“作用域链”是一样的吗?
Ruby's eval()
can be like
def showblock(&block)
puts eval("i * 3", block)
end
where block is the block passed into the function.
Instead of a block, a binding object can be passed in as well. Is the binding object the same as what is called the "scope chain" that is mentioned a lot when Javascript closure is discussed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
经过一番研究,我会说是的,它们似乎是相关的概念。
JS 中的作用域链维护了一系列执行上下文(变量绑定等),链的一端是当前执行作用域的上下文,另一端是全局作用域。创建引用自由变量的闭包需要保留该上下文列表,只要该闭包是可访问的。
Ruby Binding 对象的文档说:
我不太了解 Binding 的内部实现方式,但它似乎具有相同的目的:存储上下文以供将来评估。
After some research, I would say yes, they seem to be related concepts.
The scope chain in JS maintains a list of execution contexts (variable bindings and the like), with the context of the currently executing scope at one end of the chain, and the global scope on the other. Creating a closure that references a free variable necessitates holding on to that list of contexts as long as the closure is reachable.
The Ruby Binding object's documentation says:
I don't know as much about the internals of how Binding is implemented, but it appears to serve the same purpose: storing context for future evaluation.