I'm reading the You Don't Know JS books and am on this and Object Prototypes.
I get that to know what this
refers to I need to look at the call-site. And the call site is what this
will refer to. What I don't get is why this code isn't working as I think it should (I only wrote it to understand this
, not for any working problem or anything).
function foo() {
console.log(foo.hasOwnProperty('a')); // 1
console.log(window.hasOwnProperty('a')); // 2
console.log(this.a); // 3
this.a++;
console.log(window.hasOwnProperty('a')); // 4
}
function bar(){
foo.a = 42;
foo();
}
bar();
If you look at the first line in
bar
which creates ana
property forfoo
and assigns it the value 42. If I comment this line out, then runningconsole.log(foo.hasOwnProperty('a'));
gives me false. And if I have it run, then it returns true. But if this is the case, then callingbar
is indeed creating ana
property for foo, right? This leads to question 3.I get that at this point
window.a
does not exist.Why does this return
undefined
?this
should resolve tofoo.a
, right? Because the context ofthis
would be inbar
, correct?Bar
is the call-site. However, this remainsundefined
regardless of whetherfoo.a = 42
is commented out or not.Why does this return
true
now, after runningthis.a++
? How and why is a global variable being created?