Execution Context
Execution Context
Is the environment where our code is executed.
Composed by:
variable object,scope chainthis.
The execution context uses an ideia of Stack.
Active Execution Context...Execution Context 2Execution Context 1Global Execution Context
Inside a function, it is possible to access variables outside, by using
scope chain. So if the execution cant find a variable in currentContextit looksdownin thestack.
Every function has a variable
thisthat contains a reference to the object responsible its invocation.
There are examples that using arrow function can help like:
const obj = {
p1: 10,
getP1() {
// In this case, if a normal function declaration was used, it would steel the 'this' reference
// So since arrow functions dont inject the 'this'....'this' keeps referencing 'obj'
const fn1 = () => {
return this.p1;
}
return fn1();
}
}
console.log(obj.getP1());Closures
Is a function with static scope chain, that is defined the moment a function is created.
Thus, all functions in Javascript are closures.
Even though it seems logical that, if fn1 does not find the variable and looks at the upper scope, and then use the v1 = 100, this is wrong.
When fn1 was declared, its closure was defined, so it's fixed that the v1 it will use is the v1 = 10.
Despite static, the scope chain references objects in memory, and so, can be shared between more than one function.
Last updated