Facebook Pixel
Practical Use Cases for call, apply, and bind

How do you fix lost this in a callback in JavaScript?

The answer

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.

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.

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

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.

Success

Please Login.