2

I am a begeiner and facing a problem about javascript object this method. I attached the code for better understanding. In this code, isn't it supposed to return 'firstName' property value of 'user' object? But why it show Error?

let user = {
    firstName: "Ilya",
    sayHi: function() {
        function x() {
            return console.log(this.firstName);
        }
        return x()
    }
}

user.sayHi();

I know if i use arrow function instead of function declaration, then it work properly. Also if i use a single function as property key then it also working but i don't understand why nested function deceleration not work. Can you please help me to understand the underling cause ? Sorry for my bad English as it is my second language. Thanks in advance.

Ashik Paul
  • 486
  • 4
  • 20
smrakib
  • 43
  • 1
  • 6
  • 1
    Your function x()has its own this context, just like a regular function. The outer function, however, has the wrapping object as ‘its object’. This is why ‘this.firstName’ does not exist inside your x(), since ‘this’ is not part of that functions scope. – somethinghere Jun 17 '20 at 17:52
  • 1
    It's not about the declaration, it's about the call. – Bergi Jun 17 '20 at 18:32

1 Answers1

1

When function () {} is called without any reference like x() it's this is window object.

In your case firstName is undefined in window object that's why you getting undefined

Here is sorted example:

let user = {
    firstName: "Ilya",
    sayHi: function() {
        function x() {
            console.log(this==window); //because x is called without any reference it's this is window
            return console.log(this.firstName);
        }
        return x()
    }
}
window.firstName = "Zain"
user.sayHi();
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25