Facebook Pixel

Why does setTimeout(obj.method, 0) lose this in JavaScript?

Because the method is detached from obj when passed as a reference. setTimeout calls it with this as the global object (or undefined in strict mode). Fix it with .bind(obj), an arrow wrapper, or () => obj.method().

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Common Function Bugs in JavaScript and How to Fix Them

Use let instead of var so each iteration gets a fresh binding, or wrap the body in an IIFE that captures the current value of i as a parameter.

Because the braces are interpreted as a block body, and the object literal looks like a label statement. Wrapping the object in parentheses (n) => ({ x: 1 }) makes it an expression body that returns the object.

Because arrays are passed by reference. Mutating the parameter mutates the same object the caller holds. Copy the array ([...list]) before mutating if you want to preserve the original.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0