Javascript this.key not working when nested function use as properties

Viewed 226

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.

1 Answers

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();

Related