var x = 3;
var foo = {
x: 2,
baz: {
x: 1,
bar: function() {
return this.x;
}
}
}
var go = foo.baz.bar;
console.log(go());
console.log(foo.baz.bar());
Asked
Active
Viewed 38 times
0

Andreas
- 21,535
- 7
- 47
- 56
-
[How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Describe the problem. "It doesn't work" isn't descriptive enough to help people understand your problem. Instead, tell other readers what the expected behavior should be. Tell other readers what the exact wording of the error message is, and which line of code is producing it. Use a brief but descriptive **summary of your problem as the title** of your question."_ – Andreas Dec 04 '21 at 10:29
-
1Because when you assign the function to a variable it is no longer called in the scope of the object so `this` changes. – pilchard Dec 04 '21 at 10:29
-
You can read about `this` in JavaScript on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – jsejcksn Dec 04 '21 at 10:32