+ 6

could any one explain this code to me ? what does it do ?

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());

8th Feb 2020, 7:49 PM
Marina Khamis
Marina Khamis  - avatar
6 ответов
+ 6
Okay, I'll try. Someone knowing JS better may correct me. foo is an object, that contains another object baz. baz has an attribute x, which is 1. Outside of all these objects, a reference to the function is stored in the variable go. Now 'this' in a function refers to the place where it was called from. If the referred-to value isn't available there, it looks further out. Since go is outside of the objects, 'this' in this case is the outermost scope, so x=3. foo.baz.bar however calls the function from within baz, so 'this' now refers to baz, which has its own x=1. It's all a bit different to Python, which I'm more used to, so I'm hoping for someone else to close the gaps if there are any. 😉
8th Feb 2020, 9:53 PM
HonFu
HonFu - avatar
+ 4
When you do : var go= foo.baz.bar You are taking the function out of the baz object context and at you are storing it in a variable called go which is in the context of the global object. Now go is a function in the global object and "this" in "go" will refer to the global object and not the baz object In the other scenerio, you are not taking the function bar out of the baz object context, you are calling it directly and so it refers to the baz object
24th Apr 2021, 11:55 AM
Danny Wanyoike
Danny Wanyoike - avatar
0
Which doesn't explain a thing.
8th Feb 2020, 8:32 PM
HonFu
HonFu - avatar
0
3,1
15th Nov 2022, 4:26 PM
Shrinivas Bodke
Shrinivas Bodke - avatar
0
B
29th Apr 2024, 6:36 AM
Aakash Shinde