trekhleb/javascript-algorithms

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

utkarsh-1602 opened this issue · 4 comments

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 ?

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; }

@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

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