On 11 June 2014 10:57, Mihail Slavchev <[email protected]> wrote:
> (function() {
>   var s = "hello "
>
>   (function(name) {
>      console.log(s + name)
>   })("John")
> })()
>
> My main point is to understand how does V8 bind "s" to the scope of the
> inner function? As I said earlier, I guess V8 will introduce some new
> property that will hold a reference to the "hello " string. Is that correct?

No, copying like that wouldn't work, because s is a mutable binding,
and the function needs to capture any external update.

What V8 does is fairly standard in this regard: in a first
approximation, every scope that's entered is represented by a
"context" object carrying the bindings of that (dynamic instance of
the) scope. Furthermore, every context object contains a reference to
the context representing the (respective instance of) its enclosing
scope, so that they form a chain. Finally, every function object has a
reference to its creation context, which gives it access to the scopes
it closes over (thus the term "closure").

On top of that, V8 optimises bindings that are not accessed from inner
closures (or potentially, from 'eval' or 'with') -- they don't need to
be put into the context object, since they can never outlive their
scope. And empty context objects are not materialised at all.

In functional languages, closures are typically optimised by
"flattening" closure environments such that each closure has a copy of
all outside variables it uses, and only those (which typically are
few). This can avoid keeping large contexts alive. However, such an
optimisation is not possible when closures can capture mutable
bindings, like in JavaScript.

/Andreas

-- 
-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to