I was under the impression that the "this" keyword represents the current owner that is in scope. Obviously, this is wrong. Let me get to the code:
alert(this); // alerts as [object Window] -- Okay
function p1() {
alert(this);
}
var p2 = function() {
alert(this);
}
p1(); // alerts as undefined -- ???
p2(); // alerts as undefined -- ??
window.p1(); // alerts as [object Window] -- Okay
window.p2(); // alerts as [object Window] -- Okay
The code above first alerts [object Window], as I would expect but then the next two calls to p1() and p2() alert "this" as "undefined". The final two calls to p1() and p2() alert "this" as [object Window].
Isn't it the case that p1() and p2() exist in the global (i.e., window) scope? I thought that calling window.p1() is synonymous with calling p1(), just like calling alert() is synonymous with window.alert().
To my (C#) way of thinking, p1() and p2() are in the global scope. These functions are members of the global window object so when they refer to "this" they should be referring to [object Window]. Obviously, I'm very wrong here.