Is Ruby's "binding" the same as Scope Chain?
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?
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:
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.
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.
精彩评论