Click here to Skip to main content
15,568,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please refer to the below code. This code works correctly.

let user = { 
  firstName: "John", 
  sayHi() {   
  alert(`Hello, ${this.firstName}!`);  
 //using anonymous function 
  setTimeout(function() { 
  user.sayHi(); // Hello, John!
 }, 1000);

But when I code

setTimeout(user.sayHi, 1000); 

instead of anonymous function, it doen't work(I know why. it's because "this" of "this.firstName" loses its context ). But I can't understand, why does it work when you use anonymous function?

What I have tried:

I know I can use "bind", instead of anonymous function. But I wanna know, the reason why it works when you use anonymous function.
Updated 27-May-21 12:03pm

1 solution

The answer to this is:

SO Answer says:
In the anonymous function, this is bound to the global object (window in a browser environment).

You can find more about this (where I got that quote from) at : ecmascript 6 - this value in JavaScript anonymous function - Stack Overflow[^]
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900