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?
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.