Use bind: setTimeout(obj.method.bind(obj), 1000). Or use an arrow wrapper: setTimeout(() => obj.method(), 1000). bind permanently sets this for the returned function.
Practical Use Cases for call, apply, and bind
How do you fix lost this in a callback in JavaScript?
The answer
More FAQs in Practical Use Cases for call, apply, and bind
Use call: Array.prototype.slice.call(arguments) borrows slice to convert array-like objects to arrays. Array.prototype.forEach.call(nodeList, fn) borrows forEach for NodeLists.
Math.max.apply(null, [1, 2, 3]) returns 3. In modern JS, use spread: Math.max(...[1, 2, 3]). Both work, but spread is more readable.
In the child constructor, call the parent constructor with this: Person.call(this, name). This borrows the parent constructor and sets properties on the child instance.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.