When I run the code below and print this.property2 in the console, the JS engine returns undefined. However, if I simply print property2 instead, the compiler throws a reference error. In order to avoid this error, I need to declare the variable property2, but even then the return value is undefined.
function foo() {
var property;
console.log(this.property2)
console.log(this.property2 === property2)
console.log(property2)
}
foo.property="property value";
var property2; // adjusted to fix reference error
foo();
console.log(foo.property);
The code shows that this.property2 equals property2, so why does JavaScript handle them differently?
Here's my question: are both variables (this.property2 and property2) distinct from each other? If they are, then why does the comparison yield true? And if not, why do I have to explicitly declare property2 to fetch its value while this.property2 retrieves values without any prior declaration?
Could there be something crucial that I'm overlooking here?