trekhleb / javascript-algorithms

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings
MIT License
184.96k stars 29.83k forks source link

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

Open utkarsh-1602 opened 4 months ago

utkarsh-1602 commented 4 months ago

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 commented 4 months ago

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 commented 4 months ago

@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