I have a question about mechanism of making scope chain in JavaScript. In the Chrome browser, the results of scope chain is different according to refer variables or not.
Let me show you an example.
var A = 'Hello'
function foo() {
var B = 'World'
function bar() {
var A = 'Junhyunny'
if (A) {
const C = 'JavaScript'
if (B) {
const D = 'Post'
function baz() {
console.log(A)
console.log(B)
console.log(C)
console.log(D)
console.dir(baz)
}
}
}
baz()
}
bar()
}
foo()
[[Scope]], I expected.var A = 'Hello'
function foo() {
var B = 'World'
function bar() {
var A = 'Junhyunny'
if (A) {
const C = 'JavaScript'
if (B) {
const D = 'Post'
function baz() {
// console.log(A)
// console.log(B)
// console.log(C)
// console.log(D)
console.dir(baz)
}
}
}
baz()
}
bar()
}
foo()
[[Scope]].baz is effected by variable B, so scope Block(foo) is necessary.foo, so scope Closure(foo) is necessary.Is there some optimizing logic to make scope chain? I cannot found references for this phenomenon.