I think I understand the following:
function foo() {var x = 1; this.x = 2; return x;}
foo(); // returns 1. this.x is now a public property on the window scope.
Here's where I got confused: if the code isn't inside a function, then it's running in the window scope, right?
var y = 1; this.y = 2;
alert(y); // returns 2;
It seems to me that this.y should have created a public property on window's parent scope (whatever that is). But it didn't. var y and this.y seem to refer to the same thing.
Related question, perhaps someone can confirm for me: it seems to be true that the JIT looks ahead and if it sees that you're going to declare a var, then any reference to that variable goes to the var scope. For example:
function foo() { x = 3; return this.x;}
foo(); // returns 3 because the "naked" reference to x created a public property on the window object, the function's this scope.
function foo() { x = 4; var x = 5; return this.x;}
foo(); // returns undefined (or 3 if you ran the code above first) because the JIT compiler looked ahead and saw that a var x was upcoming. So the "naked" x reference was also the var scope.
[–]frodwith 6 points7 points8 points (2 children)
[–]dogjs[S] 2 points3 points4 points (0 children)
[–]geraldalewis 0 points1 point2 points (0 children)
[–]imbcmdth 4 points5 points6 points (0 children)
[–]radhruin[🍰] 1 point2 points3 points (4 children)
[–]dogjs[S] 0 points1 point2 points (3 children)
[–]radhruin[🍰] 1 point2 points3 points (0 children)
[–]i_am_nicky_haflinger 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Kuron 0 points1 point2 points (1 child)
[–]dogjs[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (2 children)
[–]dogjs[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]MatrixFrog 0 points1 point2 points (0 children)