trekhleb / trekhleb/javascript-algorithms

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

Open
#1,106 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
197k
Forks
31k
PR merge metrics
No merged PRs in 30d

Description

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 ?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the inline JavaScript example, focusing on the setTimeout callback, the object method, and getStatus.call(this). Check the relevant JavaScript rules for this binding and lexical scope, then reproduce the example and provide an explanation of why the result is undefined.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
developer-experience
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.