Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why this pointing to global context is giving undefined, even when global variable is defined ? #1106

Open
utkarsh-1602 opened this issue Feb 22, 2024 · 4 comments

Comments

@utkarsh-1602
Copy link

this is my program


var status = "online"

setTimeout(() => {
    
    const status = "offline"

    const data = {
        status: "not responding",
        getStatus(){
            return this.status;
        }
    }

    console.log(data.getStatus())
    console.log(data.getStatus.call(this))

}, 0);

why console.log(data.getStatus.call(this)) is returning undefined ?

@ManjulaP1012
Copy link

ManjulaP1012 commented Feb 22, 2024

I guess, when you call "data.getStatus.call(this)", getStatus method setting the value of "this" to global object. But inside getStatus method, "this.status" trying to access global object property , not the status property inside setTimeout.

If we change getStatus function to arrow function, issue will get resolved.

getStatus(){ return this.status; }

@utkarsh-1602
Copy link
Author

utkarsh-1602 commented Feb 22, 2024

@ManjulaP1012 actually the expected output should be "online" as this is pointing to global object status. but I'm not understanding why its returning undefined

@jayeshbhole7
Copy link

the reason it was returning undefined is that regular functions in Javascript have their own this context which does not automatically refer to the lexical scope of where they are defined that is why as ManjulaP1012 said that using arrow function will resolve it.

@ManjulaP1012 actually the expected output should be "online" as this is pointing to global object status. but I'm not understanding why its returning undefined

@NookieGrey
Copy link

It should work, you can see the working example here
But if you use some builders like webpack or ecosystems like codesandbox it'll not work, cose they wrap your code in IIFE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants