Reputation: 1547
I was going through JavaScript allonge#six and came to this example (short comments after each line of code):
((PI) => { //1 - Outer - PI = 3.14
((PI) => {})(100); // 2 - IIFE (LOCAL) PI = 100
// ((PI) => PI)(100) // alternative1 = LOCAL PI = 100
// ((PI) => {return PI;})(100) // alternative2 - LOCAL PI = 100
return (diameter) => diameter * PI; // 3 - PI = 3.14
})(3.14)(2)
In all of these cases, the argument bounded for PI in the outer function is passed directly to the return statement, thus ignoring the IIFE. The only way one could shadow the "PI" argument is to change the return statement to this:
((PI) => (diameter) => diameter * PI)(100)
So first Q: Is there another way to shadow the PI argument (the one bound on the outer function) aside from a closure in this case?
Additionally, I ran the code through google developer console line by line and got to a point in the code where the PI value inside the IIFE gets "overwritten" to 3.14 despite being previously bounded to 100.
Second Q:
What happens to the IIFE inside after it executes, at what point does it get its PI value overwritten to 3.14?
Upvotes: 0
Views: 54
Reputation: 2152
I found it difficult to figure out what exactly you were asking. So I just reorganised the code and added my own comments to try to make things clearer for myself, and hopefully answer some part of your questions.
var a = (function a(PI) {
// In this scope, PI = 3.14
(function b(PI) {
// PI = 100
})(100);
return function c(diameter) {
// PI = 3.14, still in scope `a`
// diameter = 2, passed in from second call
return diameter * PI;
};
});
a_result = a(3.14); // == c, with PI = 3.14
c_result = a_result(2); // c called with diameter = 2, PI = 3.14 from scope `a`
Feel free to ask more questions about this, using the names and references so I'm on the same page.
Upvotes: 1