+ 1

Why it is not showing any results in alert?

It is actually a function which outputs an object with the keyword 'this'. I think the result of code should be 'binod' but that alert box not showing any text. https://code.sololearn.com/W62QMdISZnq6/?ref=app

11th Nov 2020, 2:34 PM
Himanshu Rai
Himanshu Rai - avatar
6 Respostas
+ 9
As far as I understand, you actually created a function (returning values), not an object (forming an object with parameters). That's probably why you can't use 'this' in this context. https://www.sololearn.com/learn/JavaScript/1154/
11th Nov 2020, 3:40 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 8
Use user.name, not user.ref.name in the alert syntax
11th Nov 2020, 3:14 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
"Here, the value of 'this' should be current object". No, 'this' doesn't refer to 'that' object but to the global object. The global object on web browsers is "window" object and, as a fun fact, window.name is an empty string by default: https://developer.mozilla.org/en-US/docs/Web/API/Window/name "this" refers to the current object when: -Used in constructor functions/classes -Used within a method called with this syntax: object.method(optionalArguments) -Some other situations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this If you really want to use "this" in your code you might need to use a method or a getter function.
12th Nov 2020, 1:27 AM
Kevin ★
+ 1
Kuba Siekierzyński that's the way, but I want to access it through 'this' keyword. Here, the value of 'this' should be current object (I think), and hence, it should work this way too. So why it's not showing the name?
11th Nov 2020, 3:19 PM
Himanshu Rai
Himanshu Rai - avatar
+ 1
Kuba Siekierzyński Means in call: alert( user.ref.name) The value of ref is 'this' keyword. And in JS, the value of 'this' is calculated at run time, it takes always the current object in which it resides as a value.
11th Nov 2020, 3:22 PM
Himanshu Rai
Himanshu Rai - avatar
+ 1
Thanks Kevin ★ for telling behind the scene of this!
12th Nov 2020, 2:12 AM
Himanshu Rai
Himanshu Rai - avatar