Facebook Pixel

Why does passing obj.method to setTimeout lose this in JavaScript?

Because the method is detached from obj when passed as a reference. setTimeout calls it as a plain function, not as a method of obj. this becomes global or undefined. Fix with .bind(obj) or an arrow wrapper.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Default and Implicit this Binding in JavaScript

When a function is called as a plain function (not as a method), this is the global object in non-strict mode, or undefined in strict mode. This is the lowest-priority binding.

When a function is called as a method (obj.method()), this is the object to the left of the dot at call time. The object that owns the method call determines this.

Use .bind(obj) to permanently bind this, or wrap the method call in an arrow function (() => obj.method()), or define the method as an arrow in the object. Arrows inherit this lexically.

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
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.