Photo by Cytonn Photography on Unsplash

Let’s see the code:

What will output? The answer is Bob(immediately) … Bob(after 3s).

In a function, this is determined by how a function is called (runtime binding). It can’t be set by assignment during execution, and it may be different each time the function is called.

In this example, neither of the function assign a this (by call, bind or apply) when called, so both of this default to the global object ( window ).

However, if we log this inside test2 , thing’s gonna be different.

In this example, we log this.name directly.

In test1 , this is the upper scope(obj), so this.name is John .

In test2 , arrow functions don’t have their own this , so this points to the global object(window), and we get Bob .

--

--

Cygra

Cygra

Web Developer in Tiktok. Write about git, js, interview, etc.