When you declare a variable at the very top level, you are creating a global variable in the window object. The keyword this at the top level refers to window.
var x = 4; // same as `window.x = 4`;
console.log(x); // same as `console.log(this.x)`;
When you call obj.bar(), the this keyword refers to obj inside of bar. But inside setTimeout you have a different this, the one that refers to the caller of the callback that you pass to setTimeout. This caller doesn't specify a value for this, so instead it just becomes the window object. Therefore, in this code:
setTimeout(function() {
var x = 1;
alert(this.x);
}, 1000);
this.x is the same as window.x, which is 4 as you defined it above in the global scope.
Addressing your second example, when you assign a function to a variable you lose the context of where that function came from:
var go = foo.baz.bar;
Now when you call go() notice there is no dot in that call, which means there is no explicit object access, which means there is no implicit this. In this case you can still pass this by using call:
// outputs `3` because `this` is `window`, and `window.x` is `3`
// as declared in the global scope
alert(go());
// Will output `2` because `this` is `foo`
alert(go.call(foo));
// Will output `1` because `this` is `foo.baz`
alert(go.call(foo.baz));
// Will output `1` because the implicit value of `this` is `foo.baz`
// since we have an explicit object access in this function call
alert(foo.baz.bar());
You can avoid many of these issues with use strict. In strict mode, this will be undefined when not explicitly or implicitly defined, instead of defaulting to the window object.
setTimeout).