Check out this JavaScript code snippet:
var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
var go = foo.baz.bar;
alert(go());
alert(foo.baz.bar());
When you run the two alert
functions here, you'll notice that they display different values. The first one shows "3" and the second one shows "1". Even though it may seem like they should be referring to the same thing, there's actually a difference. It has to do with the scope in which the code is executing, but understanding exactly how it works can be a bit tricky.