I am trying to understand JavaScript functions.
just wanted to know how the value of console.log(go()); returns 6?
var x = 10;
var foo = {
x: 2,
baz: {
x : 1,
bar: function() {
return this.x + 1;
}
}
}
var go = foo.baz.bar
console.log(go()); //returns 6
console.log(foo.baz.bar()); //returns 2
can anyone pleas explain me how its returning 6?
3 Answers 3
console.log(foo.baz.bar()); will returns 2 after running the below code:
var foo = {
x: 2,
baz: {
x : 1,
bar: function() {
return this.x + 1;
}
}
}
var go = foo.baz.bar
console.log(foo.baz.bar()); //returns 2
But console.log(go()); is returning Nan in Firefox browser.
1 Comment
this in a function of JavaScript represents different objects when the function is called in different ways.
When you write foo.baz.bar(), this represents the last object in the calling object chain, that is the baz object.
However, in the following code, this doesn't represent the baz object as the final function call is not using the baz object. It belongs to the global object.
var go = foo.baz.bar;
go();
Somewhere in your code, x is a global object valued as 5, hence this.x + 1 would return 6.
Comments
This is due to the context and scope of this for both of these function calls. In the first case:
var go = foo.baz.bar;
go();
We are simply making go be the function that foo.baz.bar is, although it is only that function. You could think of it as just:
function() {
return this.x + 1;
}
Because of that this is referring to the Window, which is using the global variable x for this.x. Which is 5, giving the result 6.
In the second case we are indeed in the scope of foo.baz when we are accessing the function:
foo.baz.bar()
In this case this.x refers to x defined in foo.baz which is 1, giving the result 2.
go()returnsNaN. In what environment are you testing?go())thisrefers to the Window, so it's using the global variablexthats defined. In the second case (foo.baz.bar()) it's referring toxin the scope offoo.baz. That's why it's giving two different values.