Hy guys thanks for reading my question. So I am researching this problem since 2 days and didnt find any answer, so thanks for helping. So here is the below code:
function A(){
console.log(myVar);
}
function B(){
var myVar = 2;
A();
}
B();
So here if I run this code, from function A will get an error massage: "myVar is not defined", because it doesnt have access to the variables of function B and this is what I dont udnerstand.
So as far as I know when the code starts to run, the global execution context will be created by the javascript engine and each time the engine hits a parentheses for function call - and some other conditions are met- , javascript creates an execution context object for the function which has been called.
It should include and the scope chain, the activation object and the "this" keyword and In the scope chain should be all the variable/activation objects of the parent execution contexts
So with otherwords function A in its scope-chain-object should have function B-s all variables (but obviously it is not the case and this is what I dont understand).
But if I run this code, where function A-s definition is nested in function B:
function B(){
var myVar = 2;
A();
function A(){
console.log(myVar);
}
}
B();
So now function A will have access to the variables declaired and initialized in function B.
But in my head it shouldnt matter, where function A have been defined since it has been called in the context of function B.
Even when the this keywords value is defined in the creation phase, its value will based on, where and how the function is called, not where it has been defined.
Thanks guys that your read threw my tons of words, I really appriciate it. And thanks for every answer or any kind of article or matterial, that could help me understand this anomaly.
Cheers and thanks a lot.
In JavaScript a Lexical Environment of a function is called lexical because it is determined by the static structure of a program, not where the function is called from. It means that the outer Lexical Environment of the function A()
will be the environment within which the function A()
is declared, not called.