+ 1

Understanding "this" keyword

What will be output? 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());

24th Jul 2019, 10:55 PM
Arthur Margarian
Arthur Margarian - avatar
7 Réponses
+ 4
When you declare the go, the "this" scope refers to the global scope. That's why it returns 3. The other one is self explanatory.
24th Jul 2019, 11:25 PM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
x=3 is of global scope and hence the first call returns 3. The second accesses the internal variable x=1 SO 3,1🤔
26th Jul 2019, 2:19 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 2
Is this still the current object?
24th Jul 2019, 11:37 PM
Sonic
Sonic - avatar
+ 1
3,1
25th Jul 2019, 10:59 AM
Shiven Singh
Shiven Singh - avatar
0
1,1
5th Aug 2019, 6:52 PM
Nikki Singh
Nikki Singh - avatar
0
It's already explained, the answer is 3,1
5th Aug 2019, 7:42 PM
Shiven Singh
Shiven Singh - avatar
0
Prometheus [EXAMS]🇸🇬 by "global" do you mean a value that isn't in a function? Cause that's the only way I seem to understand it.
16th Oct 2019, 9:00 PM
SolomonDavid Akesoba
SolomonDavid Akesoba - avatar