So with the following code, I proved to myself that nested functions do indeed gain a copy of the parameters of the outer function:
var o = {};
(function(a,b,c,x){
x.f = function(){
return a.toString()+b.toString()+c.toString();
}
})(7,4,2,o);
o.f();
The code yields
742
Which means that the o.f function gains a copy of a,b, and c from the anonymous function. Otherwise, I would just get undefinedundefinedundefined
My questions are,
- First, is this always true? or are there strict circumstances? (Like, must it be an object? etc.)
- Also, what other kinds of obscure scopes exist like this in javascript? I’d love to know (i.e. what about third iterations?)
- Lastly, I’d be perfectly fine with reading a document that explicates advanced concepts on javascript scopes. Does anyone know of any good ones?
What you observe is called lexical scope. It means that the bindings of the variables in a certain scope in JavaScript are determined by where the variables appear in the code. It is always true, and it is true up to any level. The only main exception is the
thisvalue, which is dynamically scoped rather than lexically scoped. Dynamic scope means variables in the function depend on how and when the function is called. (See Lexical Scoping and Dynamic Scoping.)Example:
The result of this example will be:
In other words, the first
console.logwill logthisas a reference to theoobject, while the secondconsole.logwill logthisas a reference to thewindowobject. However, both will logxas being equal to5. The value ofthisiswindowwhen it is called in non-strict mode without a context. Sothisis not scoped lexically, but other variables, likexare. To read more about the behavior ofthissee A Short Overview ofthis.To answer your questions directly:
1. First, is this always true? or are there strict circumstances? (Like, must it be an object? etc.)
Yes, it’s true with the exception of
thisandargumentswhich change based on how the function is called. It doesn’t have to be an object, all variables are lexically scoped.2. Also, what other kinds of obscure scopes exist like this in javascript? I’d love to know (i.e. what about third iterations?)
You can go as deep as you want — inner functions can always access the variables of their outer functions.
This is actually part of another topic referred to as closures, which occur when you return a function from within another function.
3. Lastly, I’d be perfectly fine with reading a document that explicates advanced concepts on javascript scopes. Does anyone know of any good ones?
I’ve linked to a couple resources already. Another good one:
MDN: Functions and function scope (specifically the section on Nested Functions and Closures).
Also, you would be benefited from reading anything on closures, and you may also want to look up lexical scope.