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
barwhich creates anaproperty forfooand 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 callingbaris indeed creating anaproperty for foo, right? This leads to question 3.I get that at this point
window.adoes not exist.Why does this return
undefined?thisshould resolve tofoo.a, right? Because the context ofthiswould be inbar, correct?Baris the call-site. However, this remainsundefinedregardless of whetherfoo.a = 42is commented out or not.Why does this return
truenow, after runningthis.a++? How and why is a global variable being created?