+ 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());
6 Respuestas
+ 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. 😉
+ 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
0
Which doesn't explain a thing.
0
3,1
0
B