gpt4 book ai didi

ruby - Ruby的 "binding"和Scope Chain一样吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:13 24 4
gpt4 key购买 nike

Ruby 的 eval() 可以是这样的

def showblock(&block)
puts eval("i * 3", block)
end

其中 block 是传递给函数的 block 。

代替 block ,也可以传入绑定(bind)对象。绑定(bind)对象和Javascript闭包时经常提到的所谓“作用域链”是一样的吗?

最佳答案

经过一些研究,我会说是的,它们似乎是相关的概念。

JS 中的作用域链维护了一个执行上下文列表(变量绑定(bind)等),链的一端是当前执行作用域的上下文,另一端是全局作用域。创建一个引用自由变量的闭包需要持有该上下文列表,只要闭包是可访问的。

Ruby Binding 对象的文档说:

Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use. The variables, methods, value of self, and possibly an iterator block that can be accessed in this context are all retained. Binding objects can be created using Kernel#binding, and are made available to the callback of Kernel#set_trace_func.

These binding objects can be passed as the second argument of the Kernel#eval method, establishing an environment for the evaluation.

我不太了解 Binding 的内部实现方式,但它似乎服务于相同的目的:存储上下文以供将来评估。

关于ruby - Ruby的 "binding"和Scope Chain一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3171719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com