1. function test(language){
2. return function(set){
3. if(set)
4. {
5. language=set;
6. console.log("Changed "+language);
7. }
8. else
9. {
10. console.log(language);
11. }
12. }
13. }
14.
15. var a=test("en");
16. var b=test("es");
17. a("Spanish");
18. a();
19. b();
Here the execution context of lines 17 and 18 will be separate but the closure that will be created will have reference to the same instance of "language" because a function is returned in line number 15 and that will be having the same "language" in closure. Now line 18 will have a different execution context along with different instance of language because of a different initialization of function "test" in line 16. So, the output will be
Changed Spanish
Spanish
es
But now,
1. function test(){ language = "English"
2. return function(set){
3. if(set)
4. {
5. language=set;
6. console.log("Changed "+language);
7. }
8. else
9. {
10. console.log(language);
11. }
12. }
13. }
14.
15. var a=test();
16. var b=test();
17. a("Spanish");
18. a();
19. b();
Here line 17 and 18 will have different execution contexts but same instance of "language". But "a" and "b" variable's closures will have different instances of "language", just as the previous example where even after the value was changed to "Spanish" by "a" still the value shown was "es" when "b" was called because b's "language" is different from a's "language". But here as I checked the output when I've changed a's language to "Spanish" in line 17, b's "language" is also changed giving me the output as follows:
Changed Spanish
Spanish
Spanish
Now, first and second lines are understood because the same instance of "language" is present in all the "a" function calls just like the first example but b's closure must be having a different instance of language. Then why isn't the output as follows:
Changed Spanish
Spanish
English