Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
Why setTimeout doesn't work passing object's metod?

I read lot of topics (here and otherwehere) about setTimeout and this binding. Anyway there's something I need to better understand. I start with below example.

let myObj = {
  p: 'my property',
  m() { console.log(this.p); }
}

setTimeout(myObj.m, 100);  // undefined
setTimeout(function() {myObj.m()}, 100); // 'my property'

What I read from DOC is

Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the window (or global) object. It will not be the same as the this value for the function that called setTimeout.

And a way to fix using function wrapper

A common way to solve the problem is to use a wrapper function that sets this to the required

as I did in the last statement of the snippet.

My doubt: why passing a method by obj to setTimeout without wrapping it doesn't work? Passing object.method should set this to the object anyway. But maybe the direct setTimeout invocation overrides it, forcing this to be window.

I thought that maybe the use of a wrapper function, creates a new underlying scope that can refer to myObj by closure, and subsequently calling setTimeout(myObj.m(), 100) sets the right this.

Thank in advance

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!