Reputation: 13953
function f(){
function f1(){
console.log(a)
}
var a =3;
console.log(this.hasOwnProperty("a"))
console.log(f.hasOwnProperty("a"))
f1();
}
f()
Output:
false
false
3
If JS has a lexical scope then the scope of f1
is defined when f1
was defined which at that time, a
wasn't defined. Also a
is not a property of an object, then my question is why f1
finds the identifier a
?
Upvotes: 0
Views: 29
Reputation: 12894
function f(){
function f1(){
console.log(a)
}
var a =3;
console.log(this.hasOwnProperty("a"))
console.log(f.hasOwnProperty("a"))
f1();
}
f()
The snippet above, will first execute function f
and steps are as below:
//a is undefined at this step
(aka hoisting)f1
//not invoking at all
false
f1
f1
trying to console.log(a)
, and variable a
wasn't found within f1
a
at function f
The problem is not really with hoisting
as pointed out by @CertainPerformance because what really happened is that, when f1
trying to perform a logging
, it's simply perform a lexical chain lookup to find variable a
at function f
Upvotes: 1